디자인패턴 - 싱글톤

민석·2022년 7월 24일
0

디자인패턴

목록 보기
1/2

싱글톤 패턴 ?

프로세스가 실행되는중에 하나의 오브젝트만 생성되도록 강제하는 패턴

싱글톤 패턴 예제

// 패턴 적용 전
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()) // 나는 민석입니다

싱글톤패턴이 필요할때?

  • 하나의 오브젝트가 리소스를 많이 차지할때
  • 해당 오브젝트가 내부 네트워크랑 연결이되는데 이 네트워크가 1개만 존재해야할때
  • 인스턴스생성이 많이 드는 데이터베이스 연결모듈 같은곳
profile
안녕하세요 프론트엔드 개발자 양민석입니다.

0개의 댓글