00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017 #ifndef _L1394_SINGLETON_HPP
00018 #define _L1394_SINGLETON_HPP
00019
00020 #include <stdlib.h>
00021
00022
00023
00024 namespace L1394 {
00025
00026
00027
00028
00029
00030 template <class T>
00031 class SingleThreaded {
00032 public:
00033 typedef T VolatileType;
00034 };
00035
00036 template <class T>
00037 class MultiThreaded {
00038 public:
00039 typedef T VolatileType;
00040 };
00041
00042 template <class T>
00043 class CreateUsingNew {
00044 public:
00045 static T* create() {return new T();}
00046 static void destroy(T* obj) {delete obj;}
00047 };
00048
00049 template <class T>
00050 class DefaultLifetime {
00051 public:
00052 typedef void (*deleteMethod)();
00053 static void scheduleDestruction( deleteMethod d) { atexit(d); }
00054 static void onDeadReference() { }
00055 };
00056
00057 template <
00058 class T,
00059 template <class> class CreationPolicy = CreateUsingNew,
00060 template <class> class LifetimePolicy = DefaultLifetime,
00061 template <class> class ThreadingModel = MultiThreaded
00062 >
00063 class Singleton {
00064 public:
00065 static T* getInstance();
00066
00067 protected:
00068 Singleton(){};
00069
00070 private:
00071 static void destroySingleton();
00072 typedef typename ThreadingModel<T>::VolatileType InstanceType;
00073 static T* _instance;
00074 static bool destroyed;
00075 };
00076
00077
00078
00079
00080
00081 template <
00082 class T,
00083 template <class> class CreationPolicy,
00084 template <class> class LifetimePolicy,
00085 template <class> class ThreadingModel
00086 >
00087 T* Singleton<T, CreationPolicy, LifetimePolicy, ThreadingModel>::_instance = 0;
00088
00089 template <
00090 class T,
00091 template <class> class CreationPolicy,
00092 template <class> class LifetimePolicy,
00093 template <class> class ThreadingModel
00094 >
00095 bool Singleton<T, CreationPolicy, LifetimePolicy, ThreadingModel>::destroyed = false;
00096
00097
00098 template <
00099 class T,
00100 template <class> class CreationPolicy,
00101 template <class> class LifetimePolicy,
00102 template <class> class ThreadingModel
00103 >
00104 T* Singleton<T, CreationPolicy, LifetimePolicy, ThreadingModel>::getInstance() {
00105 if (!_instance) {
00106
00107 if (!_instance) {
00108 if (destroyed) {
00109 LifetimePolicy<T>::onDeadReference();
00110 destroyed = false;
00111 }
00112 _instance = CreationPolicy<T>::create();
00113 LifetimePolicy<T>::scheduleDestruction(&destroySingleton);
00114 }
00115 }
00116 return _instance;
00117 }
00118
00119 template <
00120 class T,
00121 template <class> class CreationPolicy,
00122 template <class> class LifetimePolicy,
00123 template <class> class ThreadingModel
00124 >
00125 void Singleton<T, CreationPolicy, LifetimePolicy, ThreadingModel>::destroySingleton() {
00126 CreationPolicy<T>::destroy(_instance);
00127 _instance = 0;
00128 destroyed = true;
00129 }
00130 }
00131
00132 #endif