· Last updated on

Singleton

typescriptdesign-pattern

Singleton

The Singleton pattern is different from the Single Responsibility principle defined in SOLID. The Singleton pattern is a design pattern that ensures the use of only one instance of a class (1 object - 1 class).

Avoid re-create instance

Problems

Addressing two issues at once:

Solution

Peseudocode

class Singleton {
  public static instance: Singleton;
  public variable: string;
  private constructor() {
    this.variable = "initialized";
  }

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

const hello = Singleton.getInstance();
const hi = Singleton.getInstance();
console.log(hello.variable === hi.variable); // true

Example

class Database {
  private static instance: Database;
  private constructor() {}

  public static getInstance(): Database {
    if (!this.instance) {
      this.instance = new Database();
    }
    return this.instance;
  }
}

const db = Database.getInstance();
const db2 = Database.getInstance();
console.log(db === db2);

Applicability

ProsCons
Ensures there is only a single instance of a class.However, maintaining and debugging can be difficult in multi-threaded scenarios.
The object is created only on the first access.This may violate the single responsibility principle.
It is challenging to write unit tests for client code.

References