Singleton Pattern

We start with a design pattern called a singleton. It is one of the most well-known patterns, and therefore it is a good starting point.

Singleton restricts a class to have just one instance and ensures that it is globally accessible. It might come in handy when you need to manage something from across your whole application.

The term singleton comes from math and means a set with exactly one element

By design, singletons create an instance of a class if it does not yet exist. Otherwise, they return the reference to an existing instance.

class Singleton {
  static instance;
  constructor() {
    // your logic here
  }
  static getInstance() {
    if (Singleton.instance) {
      return Singleton.instance;
    }
    Singleton.instance = new Singleton();
    return Singleton.instance;
  }
}

Now, every time we call Singleton.getInstance(), we get the same object.

Singleton.getInstance() === Singleton.getInstance(); // true

The code above looks fine at first glance, but it has some issues. Nothing restricts us from calling the Singleton constructor directly. This is when the TypeScript might come in handy.

class Singleton {
  private static instance?: Singleton;
  private constructor() {
    // your logic here
  }
  static getInstance() {
    if (Singleton.instance) {
      return Singleton.instance;
    }
    Singleton.instance = new Singleton();
    return Singleton.instance;
  }
}  

By making the Singleton constructor private, we can only call it from within the getInstance function.

Another approach that we can take is to return an instance straight from within the constructor.

class Singleton {
  static instance;
  constructor() {
    if (Singleton.instance) {
      return Singleton.instance;
    }
    Singleton.instance = this;
 
    // your logic here
  }
}
new Singleton() === new Singleton() // true

The above makes it a bit less transparent because someone might not be aware that the constructor returns the same object every time.

Singletons have a lot in common with global variables. This is also why they often are discouraged because they share their disadvantages as it might make your application less readable. Whether we consider singletons good or bad, they are one of the fundamental design patterns. Understanding them might one day come in handy. Even if you don’t decide to write them yourself, you might encounter them in some applications.

Resources

Last updated