OSDN Git Service

全体の環境を表すenvironmentの追加。
[simplecms/utakata.git] / singleton.h
1 #ifndef ___HGL___singleton___
2 #define ___HGL___singleton___
3
4 /**
5  singleton
6  そのプログラムで、一つしかオブジェクトが存在しないことを
7  保証するためのクラス。
8 */
9
10 // NULLが定義されているため。
11 #include <iostream>
12
13 template<class T>
14 class singleton {
15 public:
16
17     singleton() {}
18     virtual ~singleton(){release();}
19
20     /**
21      release
22      オブジェクトが確保されている場合、それを削除する
23      @access public
24      @return void
25     */
26     void release() {
27         if (m_pObj != NULL) {
28             delete m_pObj;
29             m_pObj = NULL;
30         }
31     }
32
33     /**
34      get
35      最初にアクセスしたときに、そのオブジェクトをnewしつつ、
36      保持するオブジェクトを返す。
37      @access public
38      @return T* オブジェクト
39     */
40     T* get() {
41         const_cast<T*>(static_cast<const singleton<T>*>(this)->get());
42     }
43
44     const T* get() const {
45         singleton<T>* p = const_cast<singleton<T>*>(this);
46         if (p->m_pObj == NULL) {
47             m_pObj = new T;
48         }
49         return static_cast<T*>(m_pObj);
50     }
51
52     //ポインターの振りをするための演算子オーバーロード
53     T* operator->() {return get();}
54     T& operator*() {return *get();}
55     const T* operator->() const {return get();}
56     const T& operator*() const {return *get();}
57
58     operator const T*() const {return get();}
59
60 private:
61
62     static T* m_pObj;   //静的に保持するオブジェクト。
63                         //初期は、必ずNULLであることが保証されている。
64
65 };
66
67 template<class T> T* singleton<T>::m_pObj = 0;
68
69 #endif