[javascript] 모듈 패턴에서의 싱글톤(Singleton) 패턴은 어떻게 구현되나요?
// 싱글톤 모듈
const singletonModule = (function () {
// 싱글톤 인스턴스
let instance;
function init() {
// 프라이빗 멤버나 함수
return {
publicMethod: function () {
console.log("싱글톤 메서드 호출");
},
publicProperty: "싱글톤 프로퍼티"
};
}
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
}
};
})();
const singletonInstance1 = singletonModule.getInstance();
const singletonInstance2 = singletonModule.getInstance();
console.log(singletonInstance1 === singletonInstance2); // true
singletonInstance1.publicMethod(); // 출력: 싱글톤 메서드 호출
위 코드에서 singletonModule
은 모듈 패턴을 사용하여 싱글톤을 구현한 것입니다. getInstance
메서드를 통해 항상 동일한 인스턴스를 반환합니다. 따라서 singletonInstance1
과 singletonInstance2
는 같은 인스턴스를 참조합니다.
이와 같은 방식으로 모듈 패턴을 사용하여 JavaScript에서 싱글톤을 구현할 수 있습니다.