- Singleton
- 하나의 클래스에 하나의 인스턴스만 가지는 패턴
- 장점 : 하나의 인스턴스를 다른 모듈들이 공유하며 사용하기 때문에, 인스턴스를 생성하는 비용이 줄어듬
- 단점
- 의존성이 올라감
- Test Driven Development에 적합하지 않음. TDD에서는 유닛 테스트를 실행하며, 이때 테스트간 순서를 바꾸어도 실행 결과가 바뀌지 않으면서, 어느 정도 독립성을 가지고 있어야 하는데, 싱글턴은 안됨.
//C++11 에서는 static의 세부사항이 변경되었기 때문에(C++17 에서 한번 더 변경됨), 더이상 DCLP
//(Double Checked Locking Pattern) 으로 Singleton을 구현하지 않아도 된다. 정적 지역 객체는
//유효기간을 갖지만, GetInstance()가 처음 호출될 때에만, 인스턴스화 된다. 포인터가 아니라
//레퍼런스로 구현한 싱글턴 객체는 인스턴스가 삭제되어도 재생성할 수 있다. 대규모 프로젝트에서는
//싱글턴을 CRTP로 구현할수도 있다.
template<typename T>
class Singleton{
public:
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
public:
static Singleton& GetInstance(){
static Singleton instance;
return instance;
}
protected:
Singleton() = default;
~Singleton() = default;
};
class DataCenter final : public Singleton<DataCenter>{
public:
DataCenter() = default;
private:
friend class Singleton<DataCenter>;
};
//JS의 Object는 그 어떤 객체와도 같지 않기 때문에, 리터럴 {} 또는 new Object로 생성한 객체는,
//그 자체로 싱글턴이다.
const obj = {
a : 27
}
const obj2 = {
a : 27
}
console.log(obj == obj2)
class Singleton{
constructor(){
if(!Singleton.instance){
Singleton.instance = this;
}
return Singleton.instance;
}
GetInstance(){
return this.instance;
}
}
const a = new Singleton()
const b = new Singleton()
console.log(a === b);