프로세스가 실행되는중에 하나의 오브젝트만 생성되도록 강제하는 패턴
// 패턴 적용 전
class Human {
constructor(name) {
this.name = name;
}
speakName() {
console.log(`나는 ${this.name}입니다`);
}
}
const minsuk = new Human('민석');
const minsu = new Human('민수');
console.log(minsuk === minsu); // false
console.log(minsuk.speakName()) // 나는 민석입니다
console.log(minsu.speakName()) // 나는 민수입니다
// 싱글톤패턴 적용
class Human {
static instance;
constructor(name) {
this.name = name;
if(!Human.instance){
Human.instance = this
}
return Human.instance
}
speakName() {
console.log(`나는 ${this.name}입니다`);
}
}
const minsuk = new Human('민석');
const minsu = new Human('민수');
console.log(minsuk === minsu); // true
console.log(minsuk.speakName()) // 나는 민석입니다
console.log(minsu.speakName()) // 나는 민석입니다