본문 바로가기
TIL

싱글톤

by 은지:) 2024. 8. 4.
728x90
반응형

 

정말 많이 쓰는 패턴 싱글톤

특정 클래스의 인스턴스가 오직 하나만 생성되도록 보장하는 디자인 패턴임

 

 

클래스 형

class Singleton {
  constructor() {
    if (Singleton.instance) {
      return Singleton.instance;
    }

    this.value = Math.random();
    Singleton.instance = this;
  }

  getValue() {
    return this.value;
  }
}

const singleton1 = new Singleton();
const singleton2 = new Singleton();

console.log(singleton1 === singleton2); // true
console.log(singleton1.getValue()); // 같은 값 출력
console.log(singleton2.getValue()); // 같은 값 출력

 

 

 

함수형

const Singleton = (() => {
  let instance;

  function createInstance() {
    const value = Math.random();
    return {
      getValue() {
        return value;
      }
    };
  }

  return {
    getInstance() {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    }
  };
})();

const singleton1 = Singleton.getInstance();
const singleton2 = Singleton.getInstance();

console.log(singleton1 === singleton2); // true
console.log(singleton1.getValue()); // 같은 값 출력
console.log(singleton2.getValue()); // 같은 값 출력

 

 

서비스단으로 보통 axios create 를 사용하니까....

 

api 호출하는 훅에 단계에서 인스턴스 만들어서 사용하면 될 듯

interceptor 는 쿠키나 로컬스토리지 관련 훅

export function createSingleton(createInstance,useInterceptor) {
  let instance;
  useInterceptor && setAuthInterceptor(createInstance);

  return () => {
    if (!instance) {
      instance = createInstance();
    }
    return instance;
  };
}

 

 

728x90
반응형

댓글