1. 개요

오직 한 개의 Object만 생성되도록 강제하는 패턴.

2. 구현

class Singleton {
  private static instance: Singleton;
  
  private constructor(private name: string) {}
 
  static getInstance(name: string) {
    if (this.instance) {
      return this.instance;
    } else {
      this.instance = new Singleton(name);
      return this.instance;  
    }
  }
 
  getName() {
    return this.name;
  }
}
 
const s1 = Singleton.getInstance("inst1");
const s2 = Singleton.getInstance("inst2");
 
console.log(s1.getName());  // inst1
console.log(s2.getName());  // inst1

참고

  • constructorprivate이므로, new 키워드를 이용하여 인스턴스를 생성할 수 없다.
  • instance 변수가 private이므로 외부에서 instance 변수에 접근할 수 없다.
  • static 메서드는 인스턴스가 아닌 클래스에 사용하는 메서드이므로, static 메서드 내부의 this는 인스턴스가 아닌 클래스를 가리킨다.
    물론 static 변수 특성상 Singleton.instance와 같은 구문으로 static 변수에 접근해도 된다.