According to Wikipedia, Singleton pattern is a software design pattern that restricts the instantiation of a class to one object.
A singleton is a class that allows only a single instance of itself to be created and gives access to that created instance. It contains static variables that can accommodate unique and private instances of itself. It is used in scenarios when a user wants to restrict instantiation of a class to only one object. This is helpful usually when a single object is required to coordinate actions across a system.
The singleton design pattern solves problems like:
- How can it be ensured that a class has only one instance?
- How can the sole instance of a class be accessed easily?
- How can the number of instances of a class be restricted?
You may have implemented this in some cases of your development and wouldn’t have known that this concept is called singleton in Design principles.
The below example illustrates a sample singleton class which suffices some of the key features.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | let _instance; class singletonExample { constructor(name,val){ if(!_instance){ this.name = name; this.val = val; _instance = this; } else { return _instance; } } } const instance1 = new singletonExample("test",1); const instance2 = new singletonExample("test",2); console.log(instance1); console.log(instance2); |
Output

As you can see in the above image, both the instances point to same object and the object is also available at global level.
References
https://en.wikipedia.org/wiki/Singleton_pattern
https://www.techopedia.com/definition/15830/singleton
Happy Coding……..)