Singleton

Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.

Applicability

Use the Singleton pattern when you need to have one and only one instance of a class and provide a global point of access to it.

Pros and Cons

Pros

  • You can be sure that a class has only a single instance.
  • You gain a global access point to that instance.
  • The singleton object is initialized only when it’s requested for the first time.

Cons

  • Violates the Single Responsibility Principle. The pattern solves two problems at the time.
  • The pattern requires special treatment in a multithreaded environment so that multiple threads won’t create a singleton object several times.
  • It may be difficult to unit test the client code of the Singleton.

Implementation

Implementation

class Singleton {
  constructor() {
    if (!Singleton.instance) {
      Singleton.instance = this;
    }

    return Singleton.instance;
  }

  getInstance() {
    return this;
  }

  someBusinessLogic() {
    // ...
  }
}

const s1 = new Singleton();
const s2 = new Singleton();

console.log(s1 === s2); // true

Applicability

  • Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program.
  • Use the Singleton pattern when you need stricter control over global variables.

Conclusion

The Singleton pattern allows you to have only one instance of a class and provides a global point of access to it.

Last updated on