//----------------------------------------------------------------------------- // Copyright(c), HL Rally: Source, 2004, All rights reserved. // The contents of this file may only be used / distributed in accordance // with the conditions listed in the supplied license, or with written // permission of the respective authors listed. //----------------------------------------------------------------------------- #ifndef SINGLETON_H #define SINGLETON_H /** * Template class to create singleton classes * * Singleton has been implemented by only allowing one static instance of * the class at any one time. * * By making the implementing class constructor and destructor private, and * giving friend access only to CSingletonABC, the class's usage may be * restricted to only the one static instance. * * ======================================================================== * Example / Usage: * * class CMyClass : public CSingletonABC * { * public: * void RandomMethod(); * ... * * private: * * // Enforce singleton by making accessable only by CSingleton * CMyClass(); * virtual ~CMyClass(); * * friend class CSingletonABC; * * ... * } * */ template class CSingletonABC { public: /** * Constructor */ CSingletonABC() { } /** * Destructor */ virtual ~CSingletonABC() { } /** * Creates the static singleton instance of T */ static T* CreateInstance() { if(!ms_pSingleton) ms_pSingleton = new T(); return ms_pSingleton; } /** * Returns a pointer to the static instance */ static T* GetInstance() { assert(ms_pInstance); return ms_pInstance; } /** * Frees the static singleton instance of T */ static void FreeInstance() { if(ms_pInstance) { delete (T *)ms_pInstance; ms_pInstance = NULL; } } protected: // Static singleton instance of T static T* ms_pInstance; }; #endif