Singleton Design Pattern - DeanHristov/ts-design-patterns-cheat-sheet GitHub Wiki

A Singleton is a creational design pattern that lets us ensure that a class has only one instance and at the same time it provides a global access point to this instance.

A Great fit when:

  1. We need a kind of global state
  2. Cross-component sharing data
  3. Single database connection within the entire app
  4. Config manager

etc...

Template

export default class Singleton {
  private static instance: Singleton;

  private constructor() {}

  public static getInstance(): Singleton {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton();
    }

    return Singleton.instance;
  }

  // Rest of the logic starts from here....
}

More info can be found on the wiki page.