JavaScript Singleton Design Patterns
What is SingleTon Pattern?
The Singleton Pattern is a design pattern that ensures a class has only one instance and provides a global point of access to it.
This single instance is unmodifiable.
It can be accessed globally throughout the application
This singleton can be shared globally across multiple files within the application. The imports of this Singleton all reference the same instance
class Singleton {
constructor() {
this.data = [];
}
addData(item) {
this.data.push(item);
}
getData() {
return this.data;
}
}
const instance = new Singleton();
Object.freeze(instance); // Prevent modification
export default instance;
Now, If you import Singleton file into multiple files, you always get the same instance.
Where to use:
When you have objects that need to coordinate actions across an application, like a database connection pool
When you want to maintain a single configuration object that’s accessible across different modules.
When you need a global logging service that any part of the application can access.
Conclusion
Singleton Pattern is powerful, but it should be used judiciously, as it creates global state and can make testing challenging. When used in the right context, however, it can help you organize and simplify the structure of your application.
If you enjoyed the article and would like to show your support, be sure to:
Follow me On Medium
Follow me On Dev
Checkout more Portfolio