CreationalTypeScriptverifiedVerified

Singleton Pattern in TypeScript

Ensures a class has only one instance and provides a global point of access to it.

How to Implement the Singleton Pattern in TypeScript

1Step 1: Define the Singleton class with a private constructor

class Singleton {
  private static instance: Singleton;

  private constructor() {
    // Private constructor prevents direct instantiation
  }

2Step 2: Implement the static getInstance method

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

  // Business methods
  doSomething(): void {
    console.log("Singleton method called");
  }
}

3Step 3: Verify only one instance exists

// Usage
const a = Singleton.getInstance();
const b = Singleton.getInstance();
console.log(a === b); // true

Singleton Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Singleton Pattern in the Real World

Think of a country’s president. There can only be one at any time. When anyone needs to communicate with the president, they don’t create a new one—they access the existing one through the official channel (the static method).