轉載地址:http://www.cnblogs.com/phoenixzq/archive/2011/05/17/2049030.html
#include
<iostream> using namespace std; //////////////////Singleton定義 /** *
@class CSingleton *
@brief 實現類把該類作爲友元, 並且把構造函數作爲非公有 *
如: *
Class C *
{ *
friend class CSingleton<C>; *
protected: *
C(){}; *
} */ template < class T> class CSingleton { public : static T*
instance() { //double
check. 鎖前和鎖後檢測,保證效率和多線程正確性 if (!m_pInstance) { //TODO:
加鎖. CMutexGuard guard(m_lock); if (!m_pInstance) { //static
T t; //m_pInstance
= &t; m_pInstance
= new T; } } return m_pInstance; }; protected : CSingleton(){};
//防止產生實例 CSingleton( const CSingleton&){};
//防止拷貝構造另一個實例 CSingleton
&operator =( const CSingleton&){};
//防止賦值構造出另一個實例 virtual ~CSingleton() { if (m_pInstance) { delete m_pInstance; m_pInstance
= NULL; } }; private : static T*
m_pInstance; //類的唯一實例 //TODO:
省略了互斥鎖成員m_lock }; //////////////////Singleton實現部分 template < class T>
T* CSingleton<T>::m_pInstance = NULL; /////////////////Singleton應用實例 class CMyLog { friend class CSingleton<CMyLog>;
//作爲友元可以訪問CSingleton的保護成員 public : void Log( char *
pszStr) { cout
<< "Log
msg: " <<
pszStr << endl; } private : CMyLog(){};
//不允許直接實例化 }; int main() { CMyLog*
pLog = CSingleton<CMyLog>::instance(); pLog->Log( "hello
word" ); system ( "pause" ); return 0; }
|