65.9K
CodeProject 正在变化。 阅读更多。
Home

单例模式的实现

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.25/5 (7投票s)

2007 年 4 月 20 日

viewsIcon

19773

downloadIcon

105

单例模式

引言

在实现应用程序系统时,你可能会发现有些对象在应用程序的整个生命周期中应该只有一个实例。你可以使用全局变量来实现它,但管理大量的全局变量在应用程序中会很困难。单例模式是一个不错的选择。该模式的目的是确保一个类只有一个实例,并提供对其的全局访问点。在本文中,我将描述一个简单的单例实现。

它是如何工作的

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 &copy);
CSingletonModel & operator = (const CSingletonModel &copy);



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;

使用代码

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;
}
© . All rights reserved.