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
{
protected:
CSingletonModel()
{
printf("CSingletonModel");
};
virtual ~CSingletonModel()
{
printf("~CSingletonModel");
};
private:
CSingletonModel(const CSingletonModel ©);
CSingletonModel & operator = (const CSingletonModel ©);
protected:
static TInstance * m_pInstance;
protected:
virtual BOOL InitInstance(){ return TRUE; }
virtual BOOL AfterGetInstance() { return TRUE; }
public:
static TInstance * GetInstance()
{
if (m_pInstance == NULL)
{
m_pInstance = new TInstance;
if (!m_pInstance->InitInstance())
{
delete m_pInstance;
m_pInstance = NULL;
return (m_pInstance);
}
}
m_pInstance->AfterGetInstance();
return (m_pInstance);
}
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[])
{
CTest *pTest1 = CTest::GetInstance();
if(pTest1)
{
printf("%s","get the only instance of class 1");
}
CTest::DestroyInstance();
CTest *pTest2 = CSingletonModel<CTest>::GetInstance();
if(pTest2)
{
printf("%s","get the only instance of class 2");
}
CSingletonModel<CTest>::DestroyInstance();
return 0;
}
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here