Dev/디자인패턴
[타입스크립트로 살펴보는 디자인패턴 5] 싱글턴 패턴
싯벨트
2024. 12. 25. 09:35
728x90
🙋♂️ 디자인패턴 구현코드 깃헙
싱글턴 패턴(Singleton Pattern)
싱글턴 패턴은 클래스 인스턴스를 하나만 만들고, 그 인스턴스로의 전역 접근을 제공합니다.
싱글턴 패턴은 특정 클래스에 객체 인스턴스가 하나만 만들어지도록 해주는 패턴이다. 싱글턴 패턴을 사용하면 필요할 때만 객체를 만들 수 있으며, 이를 지연 인스턴스 생성(Lazy Instantication)이라고 한다. 싱글턴 패턴은 필요할 때만 인스턴스를 생성하기 때문에 자원을 효율적으로 관리할 수 있고, 하나의 인스턴스만 사용하기 때문에 일관된 상태를 참조할 수 있다.
클래스에서 하나뿐인 인스턴스를 관리하도록 하며, 어디서든 그 인스턴스에 접근할 수 있도록 전약 접근 지점을 제공한다. 인스턴스가 필요한 경우 반드시 클래스 자신을 거쳐야 한다.
코드
chocolate.boiler.ts
타입스크립트는 싱글스레드이지만 멀티스레드 환경에서는 정적 초기화를 통해(싱글턴 인스턴스를 생성하고, getInstance메서드에서는 이미 생성한 인스턴스를 반환) 동시성 문제를 근본적으로 해결할 수 있지만, 애플리케이션에서 싱글턴 객체가 항상 사용되지 않는 경우 자원의 낭비가 발생할 수 있다.
export class ChocolateBoiler {
private empty: boolean;
private boiled: boolean;
private static uniqueInstance: ChocolateBoiler;
private constructor() {
console.log("== inner ==");
this.empty = true;
this.boiled = false;
}
static getInstance(): ChocolateBoiler {
if (!this.uniqueInstance) {
this.uniqueInstance = new ChocolateBoiler();
}
return this.uniqueInstance;
}
fill(): void {
if (this.isEmpty) {
this.empty = false;
this.boiled = false;
}
}
drain(): void {
if (!this.isEmpty && this.isBoiled) {
this.empty = true;
}
}
boil(): void {
if (!this.isEmpty && !this.isBoiled) {
this.boiled = true;
}
}
get isEmpty(): boolean {
return this.empty;
}
get isBoiled(): boolean {
return this.boiled;
}
}
ChocolateBoiler.getInstance();
ChocolateBoiler.getInstance();