싱글톤 패턴(Singleton Pattern)은 소프트웨어 디자인 패턴 중 하나로, 클래스의 인스턴스를 하나만 생성하고, 그 인스턴스에 접근할 수 있는 전역적인 접근점을 제공하는 패턴, 주로 전역 상태를 관리하거나, 시스템 내에서 공통으로 사용되는 리소스나 설정을 관리할 때 사용 됨
하나의 인스턴스를 기반으로 해당 인스턴스를 다른 모듈들이 공유하여 사용하기 때문에 신스턴스를 생성할 때 드는 비용이 감소
그렇기 때문에 인스턴스 생성에 많은 비용이 드는 I/O 바운드 작업에 많이 사용 됨
의존성이 높아지면, TDD(Test Driven Development)를 할 때 걸림돌이 될 수 있음
TDD를 할 때 단위 테스트를 주로 하는데, 단위 테스트는 테스트를 하는 각각의 단위가 서로 독립적이여야 함
의존성이 있는경우 다른 단위의 테스트 결과에 따라서 다른 단위 테스트에 영향을 줄 수 있기 때문
싱글톤턴은 미리 생성된 하나의 인스턴스를 기반으로 구현하는 패턴이므로 각 테스트마다 독립정인 인스턴스를 만들기가 어려움
가장 간단한 싱글톤 패턴 구현 방법은 객체 리터럴을 사용하는 것
JavaScript의 객체 리터럴은 본질적으로 싱글톤 임
javascript코드 복사
const Singleton = {
property: 'I am a singleton',
method: function() {
console.log(this.property);
}
};
// 사용 예시
Singleton.method(); // "I am a singleton"
클로저를 이용하여 싱글톤 패턴을 구현할 수도 있음
javascript코드 복사
const Singleton = (function() {
let instance;
function createInstance() {
const object = new Object('I am the instance');
return object;
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
// 사용 예시
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
ES6의 클래스를 사용하여 싱글톤 패턴을 구현할 수 있음
javascript코드 복사
class Singleton {
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
Singleton.instance = this;
this.property = 'I am a singleton instance';
}
method() {
console.log(this.property);
}
}
// 사용 예시
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true
instance1.method(); // "I am a singleton instance"
instance2.method(); // "I am a singleton instance"
JavaScript 모듈 패턴을 사용하여 싱글톤 패턴을 구현할 수 있음
javascript코드 복사
const Singleton = (function() {
let instance;
function init() {
return {
property: 'I am a singleton',
method: function() {
console.log(this.property);
}
};
}
return {
getInstance: function() {
if (!instance) {
instance = init();
}
return instance;
}
};
})();
// 사용 예시
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
instance1.method(); // "I am a singleton"
instance2.method(); // "I am a singleton"
싱글톤 패턴을 사용하면 클래스의 인스턴스가 하나만 존재하도록 보장할 수 있으며, 전역 상태를 관리하는 데 도움이 됨
하지만 남용할 경우 전역 상태 관리의 복잡성이 증가할 수 있으므로 필요할 때 신중하게 사용하는 것이 좋다