Design Pattern

[Design Pattern] 싱글톤 패턴

0so0 2023. 8. 1. 08:43
728x90
반응형
SMALL

싱글톤(Singleton)패턴에 대한 정리

 

싱글톤(Singleton)

인스턴스가 하나뿐인 특별한 객체를 만들 수 있게 해주는 패턴
스레드풀이나, 대화상자를 구현할때 2개 이상의 인스턴스 생성 시 일관성 없는 결과 생성, 자원 낭비를 방지하고자 할때 사용

 

사용 이유

  • 메모리 낭비 방지
  • DBCP(DataBase Connection Pool) 처럼 공통된 객체를 여러 개 생성해서 사용할 때 편리
  • 인스턴스가 절대적으로 한 개만 존재하는 것을 보증하고 싶을 경우
  • 다른 클래스의 인스턴스들이 데이터를 공유하기 쉬움

 

구조

사용 예시

class ChocolateBoiler {
    ChocolateBoiler1();
    ~ChocolateBoiler1();

    public:
        static ChocolateBoiler& getinstance() {
        	// instance는 getinstance 함수의 정적지역변수
            static ChocolateBoiler* instance = new ChocolateBoiler();
            return *instance;
        }
        void fill();
        void drain();
        void boil();
        bool isEmpty() const;
        bool isBoiled() const;
};

 

 

* 잘못된 예시

class ChocolateBoiler {
    static ChocolateBoiler* _uniqueInstance;
    bool _empty;
    bool _boiled;
    ChocolateBoiler();
    ~ChocolateBoiler();

    public:
        static ChocolateBoiler* getInstance();
        void fill();
        void drain();
        void boil();
        bool isEmpty() const;
        bool isBoiled() const;
};

ChocolateBoiler* ChocolateBoiler::getInstance()
{
    if( _uniqueInstance == 0 ) {
        cout << "Creating unique instance" << endl;
        _uniqueInstance = new ChocolateBoiler();
    }
    cout << "Returning instance of Chocolate Boiler“ << endl;
    return _uniqueInstance;
}

위와 같이 사용시 _uniqueInstance가 초기화 되어있지 않아, 초기화 되어있지 않은 변수 참조 에러 발생 가능

 

CRTP로 구현한 싱글톤

CRTP(Curiously Recurring Template Pattern)

부모가 템플릿이고, 자식클래스를 만들 때 자신의 클래스 이름을 부모에게 전달하는 기술
// The Curiously Recurring Template Pattern (CRTP)
template<class T>
class Base
{
    // methods within Base can use template to access members of Derived
};
class Derived : public Base<Derived>
{
    // ...
};

 

template <typename T>
class Singleton
{
protected:
    Singleton(){};
private:
    Singleton(const Singleton&) ;
    void operator=(const Singleton&);
public:
    static T& GetInstance()
    {
      static T instance;
      return instance;
    }
};

class Keyboard : public Singleton<Keyboard> {};
class Mouse : public Singleton<Mouse> {};

int main(void)
{
    Keyboard& keyboard = Keyboard::GetInstance();
    Mouse& mouse = Mouse::GetInstance();

    return 0;
}
728x90
반응형
LIST

'Design Pattern' 카테고리의 다른 글

[Design Pattern] MVVM 패턴  (0) 2023.10.03
[Design Pattern] 컴포지트 패턴  (0) 2023.08.16
[Design Pattern] 디자인 패턴 종류  (0) 2023.07.03