Singleton

The Singleton pattern is one of the most commonly used design patterns across the software development industry. The problem that it aims to solve is to maintain only a single instance of a class.

When we create two new instance of Counter, The instance of both objects are different.

function Counter() {
  this.count = 0;

  this.increment = () => {
    this.count++;
  };

  this.decrement = () => {
    this.count--;
  };
}

let counter1 = new Counter();
let counter2 = new Counter();
console.log(counter1 === counter2); // false

This Singleton example is specific to Counter. We can accept the Function() constructor as params inside the Singleton and use a Map data structure to store all the instances.

const Singleton = (function () {
  let instance;

  function createInstance() {
    if (!instance) {
      instance = new Counter();
    }
    return instance;
  }

  return {
    createInstance,
  };
})();

counter1 = Singleton.createInstance();
counter2 = Singleton.createInstance();
console.log(counter1 === counter2); // true