Design Patterns: Applying Singleton in JavaScript
Hello HaWkers! Today, we're going to explore one of the most well-known and useful design patterns: Singleton. It can be a powerful tool for keeping your JavaScript code organized and efficient.
What is the Singleton pattern?
Singleton is a design pattern that restricts the creation of an object to a single instance. This pattern is useful when a single object needs to coordinate actions throughout the system.
Implementing Singleton in JavaScript
Let's see how we can apply the Singleton pattern in JavaScript.
class Singleton { constructor(data) { if (Singleton.instance) { return Singleton.instance; } Singleton.instance = this; this.data = data; } getData() { return this.data; }}const instanceOne = new Singleton('Data for instance one');console.log(instanceOne.getData()); // Data for instance oneconst instanceTwo = new Singleton('Data for instance two');console.log(instanceTwo.getData()); // Data for instance one
Note that, even trying to create a new Singleton instance with new data, the information returned is the first. This is because when instantiating the Singleton class for the second time, the first created instance is returned.
Why use the Singleton pattern?
Singleton can be useful when we want to control access to some shared resource, such as a database connection or a log file.
I hope this post helped you better understand the Singleton pattern and how to apply it in JavaScript. For a more in-depth introduction to JavaScript, check out our post on Introduction to Modern JavaScript.
Until next time, HaWkers!