TIL
싱글톤
은지:)
2024. 1. 28. 16:08
728x90
반응형
1. 하나의 객체 인스턴스만 존재함
2. 스테틱 함수로 객체 접근
class S {
constructor() {
if (S.instance) {
return console.log('already instantiated');
}
S.instance = this;
this.version = Date.now();
this.config = 'test';
}
static getInstance() {
if (!this.instance) {
this.instance = new S();
}
return this.instance;
}
}
const s1 = new S();
console.log(s1);
const s2 = new S();
console.log(s2);
s1 === s2
콘솔 찍어도 true 가 나옴
싱글톤을 한번 더 실행하려고 했을 때
두번째는 인스턴스가 생성이 되지 않음. 이미 싱글톤이 있다고 나옴
const s1 = S.getInstance();
console.log(s1);
const s2 = S.getInstance();
console.log(s2);
요거 찍어봤을 때
s1 === s2
콘솔 찍어도 true 가 나옴
장점
하나의 인스턴스에서 리소스를 관리할 수 있음
코드 중복을 관리할 수 있음
static 을 통해서 앱 전역에서 이 singleton 을 접근할 수 있음
728x90
반응형