/* * ===================================================================================== * * Filename: singleton.h * * Description: singleton class definition. * * Version: 1.0 * Created: 09/08/2018 * Revision: none * Compiler: gcc * * Author: zhulin, shzhulin3@jd.com * Company: JD.com, Inc. * * ===================================================================================== */ #ifndef __SINGLETON_H__ #define __SINGLETON_H__ #include "lock.h" #include "namespace.h" TTC_BEGIN_NAMESPACE template struct CreateUsingNew { static T* Create (void) { return new T; } static void Destroy(T* p) { delete p; } }; template class CreationPolicy = CreateUsingNew> class CSingleton { public: static T* Instance (void); static void Destroy (void); private: CSingleton (void); CSingleton (const CSingleton&); CSingleton& operator= (const CSingleton&); private: static T* _instance; static CMutex _mutex; }; TTC_END_NAMESPACE TTC_USING_NAMESPACE //implement template class CreationPolicy> CMutex CSingleton::_mutex; template class CreationPolicy> T* CSingleton::_instance = 0; template class CreationPolicy> T* CSingleton::Instance (void) { if (0 == _instance) { CScopedLock guard(_mutex); if (0 == _instance) { _instance = CreationPolicy::Create (); } } return _instance; } /* BUGFIX by ada*/ #if 0 template class CreationPolicy> void CSingleton::Destroy (void) { return CreationPolicy::Destroy (_instance); } #endif template class CreationPolicy> void CSingleton::Destroy (void) { if(0 != _instance) { CScopedLock guard(_mutex); if(0 != _instance) { CreationPolicy::Destroy (_instance); _instance = 0; } } return; } #endif //__SINGLETON_H__