00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017 #ifndef __SINGLETON_H__
00018 #define __SINGLETON_H__
00019
00020 #include "../debug/DebugUtils.h"
00021
00022 namespace oasys {
00023
00042 template<typename _Class, bool _auto_create = true>
00043 class Singleton;
00044
00049 class SingletonBase {
00050 public:
00053 SingletonBase();
00054
00056 virtual ~SingletonBase();
00057
00059 static SingletonBase** all_singletons_;
00060
00062 static int num_singletons_;
00063
00064 private:
00069 class Fini {
00070 public:
00072 ~Fini();
00073 };
00074
00075 static Fini fini_;
00076 };
00077
00081 template<typename _Class>
00082 class Singleton<_Class, true> : public SingletonBase {
00083 public:
00084 static _Class* instance() {
00085
00086
00087
00088 if(instance_ == 0) {
00089 instance_ = new _Class();
00090 }
00091 ASSERT(instance_);
00092
00093 return instance_;
00094 }
00095
00096 static _Class* create() {
00097 if (instance_) {
00098 PANIC("Singleton create() method called more than once");
00099 }
00100
00101 instance_ = new _Class();
00102 return instance_;
00103 }
00104
00105 static void set_instance(_Class* instance) {
00106 if (instance_) {
00107 PANIC("Singleton set_instance() called with existing object");
00108 }
00109 instance_ = instance;
00110 }
00111
00112 protected:
00113 static _Class* instance_;
00114 };
00115
00119 template<typename _Class>
00120 class Singleton<_Class, false> : public SingletonBase {
00121 public:
00122 static _Class* instance()
00123 {
00124
00125
00126 ASSERT(instance_);
00127 return instance_;
00128 }
00129
00130 static _Class* create()
00131 {
00132 if (instance_)
00133 {
00134 PANIC("Singleton create() method called more than once");
00135 }
00136
00137 instance_ = new _Class();
00138 return instance_;
00139 }
00140
00141 static void set_instance(_Class* instance)
00142 {
00143 if (instance_)
00144 {
00145 PANIC("Singleton set_instance() called with existing object");
00146 }
00147 instance_ = instance;
00148 }
00149
00150 protected:
00151 static _Class* instance_;
00152 };
00153
00164 template<typename _Class>
00165 class SingletonRef {
00166 public:
00167 _Class* operator->() {
00168 return Singleton<_Class>::instance();
00169 }
00170 };
00171
00172 }
00173
00174 #endif // __SINGLETON_H__