'Developer/Design Patterns'에 해당되는 글 27건

  1. 2014.05.17 메크로를 이용한 SingleTon 자동생성 1

// 싱글톤 : 오직 하나의 인스턴스만을 생성하는 설계 기법

// 싱글톤 코드의 생성을 자동화(전형적인 방식, 매크로)

 

#include <iostream>

using namespace std;

 

// 복사 금지 매크로

#define MAKE_NO_COPY(CLASSNAME)                                             \

        private:                                                            \

               CLASSNAME(const CLASSNAME&);                                 \

               CLASSNAME& operator=(const CLASSNAME&);

 

// 싱클톤 패턴 생성 매크로

#define DECLARE_SINGLETONE(CLASSNAME)                                       \

        MAKE_NO_COPY(CLASSNAME)                                             \

        private:                                                            \

               CLASSNAME() {}                                               \

               static CLASSNAME* sInstance;                                 \

        public:                                                             \

               static CLASSNAME& getInstance();

 

#define IMPLEMENT_SINGLETON(CLASSNAME)                              \

               CLASSNAME* CLASSNAME::sInstance=0;                   \

                                                                    \

               CLASSNAME& CLASSNAME::getInstance() {                \

                       if(sInstance==0)                             \

                              sInstance=new CLASSNAME;              \

                              return *sInstance;                    \

               }                                                                                 

 

class Cursor {

        DECLARE_SINGLETONE(Cursor)

};

IMPLEMENT_SINGLETON(Cursor)

 

 

int main(void) {

        Cursor& c1 = Cursor::getInstance();

        Cursor& c2 = Cursor::getInstance();

 

        cout << "&c1 = " << &c1 << endl;

        cout << "&c2 = " << &c2 << endl;

        return 0;

}

Posted by No names
,