Web/JavaScript

[TypeScript] Singleton Pattern

llHoYall 2021. 7. 5. 18:48

Singleton is the most popular design pattern.

It is a kind of creational design pattern and it ensures that only one instance.

Code

class Singleton {
  private static instance: Singleton;

  private constructor() { }

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

We can get the same single instance using getInstance() anywhere in the same project code.

Test

class Singleton {
  private static instance: Singleton;

  private constructor() { }

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

const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();

console.log(instance1 === instance2); // true

Usage

We can add more business logic that we want to keep with a single instance.

class Singleton {
  private static instance: Singleton;

  private constructor(public counter: number) { }

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

  public addCounter(): void {
    ++this.counter;
  }
}

const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();

instance1.addCounter()
instance2.addCounter()

console.log(instance1.counter); // 2
console.log(instance2.counter); // 2

In this example, we add a variable for the counter and it is shared through the entire project.

반응형