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
반응형
'TIL' 카테고리의 다른 글
타입스크립트 공변성, 반공변성 (0) | 2024.08.11 |
---|---|
타입스크립트 오버로딩 (0) | 2024.08.11 |
클로저 - hof - 리액트 - hoc - class (0) | 2024.08.04 |
es5은 어떻게 브라우저에서 동작했을까 & UMD (0) | 2024.07.28 |
tanstack Query v5 (0) | 2024.07.28 |
댓글