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

  1. 2014.05.17 싱글톤 패턴 & RAII

#include <iostream>

using namespace std;

 

class Mutex {

public:

        void lock() {

               cout << "Mutex::lock " << endl;

        }

 

        void unlock() {

               cout << "Mutex::unlock " << endl;

        }

};

 

// 객체의 생성과 동시에 자원을 획득하고 객체가 파괴될

// 자원을 해제하는 기법 (RAII, Resource Acquisition Is Initialization)

 

// 안드로이드에서는 Autolock이라는 클래스로 사용됨

 

template<typename T> class ScopeLock {

        T& obj;

 

public:

        ScopeLock(T* o) : obj(*o) { obj.lock(); }

        ScopeLock(T& o) : obj(o)  { obj.lock(); }

        ~ScopeLock() { obj.unlock(); }

};

 

 

class Cursor {

private:

        Cursor() {}

        Cursor(const Cursor& c);

        Cursor& operator=(const Cursor& c);

 

        static Cursor* sInstance;

        static Mutex mutex;

 

public:

        static Cursor& getInstance() {

               //-------------------------

               {

                       ScopeLock<Mutex> sl(mutex);           //생성되면서 Lock

                       if(sInstance==0)

                              sInstance=new Cursor;

               } //소멸되면서 unLock

               //-------------------------

               return *sInstance;

        }

};

 

Cursor* Cursor::sInstance;

Mutex Cursor::mutex;

 

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
,