![싱글턴](/images/patterns/cards/singleton-mini.png?id=914e1565dfdf15f240e766163bd303ec)
타입스크립트로 작성된 싱글턴
싱글턴은 같은 종류의 객체가 하나만 존재하도록 하고 다른 코드의 해당 객체에 대한 단일 접근 지점을 제공하는 생성 디자인 패턴입니다.
싱글턴은 전역 변수들과 거의 같은 장단점을 가지고 있습니다: 매우 편리하나 코드의 모듈성을 깨뜨립니다.
싱글턴에 의존하는 클래스를 다른 콘텍스트에서 사용하려면 싱글턴도 다른 콘텍스트로 전달해야 합니다. 대부분의 경우 이 제한 사항은 유닛 테스트를 생성하는 동안 발생합니다.
복잡도:
인기도:
사용 사례들: 많은 개발자는 싱클턴을 안티패턴으로 간주합니다. 그래서 타입스크립트 코드에서의 사용이 감소하고 있습니다.
식별: 싱글턴은 같은 캐싱 된 객체를 반환하는 정적 생성 메서드로 식별될 수 있습니다.
개념적인 예시
이 예시는 싱글턴 패턴의 구조를 보여주고 다음 질문에 중점을 둡니다:
- 패턴은 어떤 클래스들로 구성되어 있나요?
- 이 클래스들은 어떤 역할을 하나요?
- 패턴의 요소들은 어떻게 서로 연관되어 있나요?
index.ts: 개념적인 예시
/**
* The Singleton class defines an `instance` getter, that lets clients access
* the unique singleton instance.
*/
class Singleton {
static #instance: Singleton;
/**
* The Singleton's constructor should always be private to prevent direct
* construction calls with the `new` operator.
*/
private constructor() { }
/**
* The static getter that controls access to the singleton instance.
*
* This implementation allows you to extend the Singleton class while
* keeping just one instance of each subclass around.
*/
public static get instance(): Singleton {
if (!Singleton.#instance) {
Singleton.#instance = new Singleton();
}
return Singleton.#instance;
}
/**
* Finally, any singleton can define some business logic, which can be
* executed on its instance.
*/
public someBusinessLogic() {
// ...
}
}
/**
* The client code.
*/
function clientCode() {
const s1 = Singleton.instance;
const s2 = Singleton.instance;
if (s1 === s2) {
console.log(
'Singleton works, both variables contain the same instance.'
);
} else {
console.log('Singleton failed, variables contain different instances.');
}
}
clientCode();
Output.txt: 실행 결과
Singleton works, both variables contain the same instance.