Singleton Class in Javascript

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.


Singleton Class output
Singleton Class 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.


Happy Coding……..)

Tagged as: ,