TuttleOFX
1
|
00001 #ifndef Singleton_HPP 00002 #define Singleton_HPP 00003 00004 /** 00005 * @brief Singleton<ClassSingleton> Can transform a class into Singleton (by inheriting this class) 00006 * 00007 * @par Purpose 00008 * Forcing (limit) the presence of a single instance of a class 00009 * 00010 * @par Usage 00011 * The class T, to use as Singleton, must derive from this class (: public Singleton <T>). 00012 * The macro MAKE_SINGLETON (T) create necessary elements (including constructors). 00013 */ 00014 template <class T> 00015 class Singleton 00016 { 00017 private: 00018 static T* inst; 00019 00020 Singleton( const Singleton& ) {} 00021 Singleton& operator=( const Singleton& ) {} 00022 00023 protected: 00024 Singleton() {} 00025 virtual ~Singleton() = 0; 00026 00027 public: 00028 /** 00029 * @brief return the unique instance of Singleton<T> class 00030 * @return T the unique instance of Singleton<T> class 00031 */ 00032 static T& instance() 00033 { 00034 if( !inst ) 00035 inst = new T; 00036 return *inst; 00037 } 00038 00039 /** 00040 * @brief destroy the unique instance of Singleton<T> class 00041 */ 00042 static void destroy() 00043 { 00044 delete inst; 00045 inst = NULL; 00046 } 00047 00048 }; 00049 00050 template <class T> 00051 T * Singleton<T>::inst = NULL; 00052 00053 template <class T> 00054 Singleton<T>::~Singleton() {} 00055 00056 ///macro to implement singleton. Use it in derived class declaration 00057 #define MAKE_SINGLETON( Class ) \ 00058 public: \ 00059 friend class Singleton < Class >; \ 00060 private: \ 00061 Class() {} \ 00062 ~Class() {} 00063 00064 ///macro to implement singleton. Use it in derived class declaration 00065 #define MAKE_SINGLETON_WITHCONSTRUCTORS( Class ) \ 00066 public: \ 00067 friend class Singleton < Class >; \ 00068 private: \ 00069 Class(); \ 00070 ~Class(); 00071 00072 #endif