A implemetion of Singleton Pattern






1.25/5 (7 votes)
Apr 20, 2007

19302

87
Singleton Pattern
Introduction
When you implement your application system, you may find some objects that should have only one instance throughout the application lifetime. You can implement it using global variable, but it is difficult to manage many global variables in application. Singleton Pattern is a good choice. the aim of the pattern is to ensure a class only has one instance, and provide a global point of access to it.In this article I will describe a simple singleton implementations
How is it working
template <class TInstance> class CSingletonModel { // forbid to new CSingletonModel directly protected: CSingletonModel() { printf("CSingletonModel"); }; virtual ~CSingletonModel() { printf("~CSingletonModel"); }; // forbid to copy construct function private: CSingletonModel(const CSingletonModel ©); CSingletonModel & operator = (const CSingletonModel ©); protected: //the only instance of class static TInstance * m_pInstance; protected: //initialize instance virtual BOOL InitInstance(){ return TRUE; } //the event function before the GetInstance() return virtual BOOL AfterGetInstance() { return TRUE; } public: //get the only instance static TInstance * GetInstance() { //create the instance if (m_pInstance == NULL) { m_pInstance = new TInstance; //init object. if (!m_pInstance->InitInstance()) { delete m_pInstance; m_pInstance = NULL; return (m_pInstance); } } m_pInstance->AfterGetInstance(); return (m_pInstance); } //destroy the only Instance static void DestroyInstance() { if (m_pInstance) { delete m_pInstance; m_pInstance = NULL; } }; template <class TInstance> TInstance* CSingletonModel<TInstance>::m_pInstance = NULL;
Using the code
class CTest:public CSingletonModel<CTest> { public: CTest() { printf("CTest"); }; ~CTest() { printf("~CTest"); }; public: virtual BOOL InitInstance() { return TRUE; } virtual BOOL AfterGetInstance() { return TRUE; } }; int _tmain(int argc, _TCHAR* argv[]) { //the first method CTest *pTest1 = CTest::GetInstance(); if(pTest1) { printf("%s","get the only instance of class 1"); } CTest::DestroyInstance(); //the second method CTest *pTest2 = CSingletonModel<CTest>::GetInstance(); if(pTest2) { printf("%s","get the only instance of class 2"); } CSingletonModel<CTest>::DestroyInstance(); return 0; }