Singleton模式笔记
在C++中,尽量用Singleton替换全局变量是个很好的建议,Singleton一般如下:
class CSingleton
{
private:
static CSingleton* m_pInstance;
private:
CSingleton(){}
~CSingleton(){}
CSingleton( const CSingleton& );
CSingleton& operator=( const CSingleton& );
public:
static CSingleton* GetInstance()
{
if( m_pInstance == NULL )
{
m_pInstance = new CSingleton;
}
return m_pInstance;
}
};
CSingleton* CSingleton::m_pInstance = NULL;
这种实现有个缺点:单例对象无法销毁.虽然泄漏的内存在程序结束后可由操作系统回收,但是会造成资源泄漏,如网络连接、COM引用等.这些操作系统是无法自动回收的.因此需要在程序结束前销毁这个单例对象.标准C库提供了一个很方便的函数:atexit,通过其注册的函数能在程序结束时自动调用(调用次序是后进先出),可以通过此函数实现单例对象的自动销毁功能:
{
private:
static CSingleton* m_pInstance;
private:
CSingleton(){}
~CSingleton(){}
CSingleton( const CSingleton& );
CSingleton& operator=( const CSingleton& );
public:
static CSingleton* GetInstance()
{
if( m_pInstance == NULL )
{
m_pInstance = new CSingleton;
}
return m_pInstance;
}
};
CSingleton* CSingleton::m_pInstance = NULL;
class CSingleton
{
private:
static CSingleton* m_pInstance;
private:
CSingleton(){}
~CSingleton(){}
CSingleton( const CSingleton& );
CSingleton& operator=( const CSingleton& );
public:
static CSingleton* GetInstance()
{
if( m_pInstance == NULL )
{
atexit( CSingleton::Destory );
m_pInstance = new CSingleton;
}
return m_pInstance;
}
static void Destory()
{
if( m_pInstance != NULL )
{
delete m_pInstance;
m_pInstance = NULL;
}
}
};
CSingleton* CSingleton::m_pInstance = NULL;
{
private:
static CSingleton* m_pInstance;
private:
CSingleton(){}
~CSingleton(){}
CSingleton( const CSingleton& );
CSingleton& operator=( const CSingleton& );
public:
static CSingleton* GetInstance()
{
if( m_pInstance == NULL )
{
atexit( CSingleton::Destory );
m_pInstance = new CSingleton;
}
return m_pInstance;
}
static void Destory()
{
if( m_pInstance != NULL )
{
delete m_pInstance;
m_pInstance = NULL;
}
}
};
CSingleton* CSingleton::m_pInstance = NULL;
Singleton模式的另一种实现,简称:Meyers 单件,其示例如下:
class CSingleton
{
private:
CSingleton(){}
~CSingleton(){}
CSingleton( const CSingleton& );
CSingleton& operator=( const CSingleton& );
public:
static CSingleton& GetInstance()
{
static CSingleton instance;
return instance;
}
};
{
private:
CSingleton(){}
~CSingleton(){}
CSingleton( const CSingleton& );
CSingleton& operator=( const CSingleton& );
public:
static CSingleton& GetInstance()
{
static CSingleton instance;
return instance;
}
};