Contact Me

Singleton

 This pattern ensures that a class has only one instance, and provides a global point of access to that instance. This can be useful when you want to ensure that there is only one instance of a class in your application, and when you want to provide a global point of access to that instance.


Here is an example of the singleton pattern in JavaScript:


class Singleton {

constructor() {

  if (!Singleton.instance) {

  Singleton.instance = this;

}

return Singleton.instance;

}

}

const instance1 = new Singleton();

const instance2 = new Singleton();

console.log(instance1 === instance2);

// Output: true


In this example, the Singleton class is a class that represents the singleton object. The Singleton class has a private static property called instance, which is used to store the singleton instance. The Singleton class also has a constructor, which checks if an instance of the Singleton class already exists.

If an instance does not exist, the constructor creates a new instance and stores it in the instance property. If an instance does exist, the constructor returns the existing instance.

To use the singleton pattern, we create an instance of the Singleton class using the new operator, and then access the instance using the Singleton.instance property. This ensures that there is only one instance of the Singleton class in our application, and that we have a global point of access to that instance.