Singleton~ Design patterns ~

Singleton

In this section of the book, we will learn about six of my favorite design patterns. The first one is called "singleton". Whenever we force the creation of one and only one instance of a class, we use the singleton pattern. Think about a class that we can initialize only once.

In JavaScript, the implementation of this pattern is often done via a static class function.

let cache;
class A {
  static getInstance() {
    if (cache) return cache;
    return cache = new A();
  }
}

const x = A.getInstance();
const y = A.getInstance();

console.log(x === y); // true

The cache variable keeps the created instance of the class. If we attempt to create a new one, we will get the same object. That is why x and y point to the same thing.

Another popular way to create a singleton is to use a factory function:

let cache;
class A {
  // ...
}

function getInstance() {
  if (cache) return cache;
  return cache = new A();
}

const x = getInstance();
const y = getInstance();

console.log(x === y); // true

I prefer this approach because it eliminates the option of someone using new <MyClass> directly.