Intro
The Singleton pattern falls in the category of Creational Design Patterns. This pattern enable us to create a single instance of a class regardless how many times you call it. To understand why will we ever need to use this pattern we should understand the issue when not using this pattern.
The Problem
While developing a software there are cases when we need a single instance of an class, ony a single and same instance should be always returned. The best examples are the config object and the logger object.
Configuration Object
Suppose you have a web application which used environment variables and you are intended to use the that config object as a global object your application to access the required credentials and keys for various use cases.
Let’s see the scenarios when the Config Class is not singleton:
- Configs are loaded and created multiple times.
- Each module can get different configs making it inconsistent.
- If you are loading the configs from remote store, it also leads to different values.
- During testing each tech suit may load/fetch different configuration which will be hard to debug.
Logger Object
The logger will undergo the same fate. We initiate loggers in each module with module name for easy debugging but:
- Every module will create it’s own logger instance
- This increase memory usages
- Each logger object may not get the correct config.
The Solution
The solutions to such problem is to limit the creation of multiple objects for a class. Let’s have a look at the code on how to do this.
1 | public class Config { |
The rules for making a class Singleton are:
- Make the constructor private. This will not allow object creation.
- Making the
instancevariable final means it cannot be reassigned. - Using the static method
GetInstancewill allow others to get the instance of config class. - Using
statichere makes theinstancevariable the property of the class which will remain in-memory for the lifetime of the application.
The TypeScript code is exactly same:
1 | export class Config { |
Conclusion
I was trying to learn how to implement the same singleton pattern in JavaScript (no, not with ES6) and I discovered a rabbit hole of hacks while doing that. Meanwhile I absorb the singleton pattern using JavaScript, you can feel free to explore more of the design patterns or trouble yourself with the JavaScript ES5 implementations of a Singleton!