C++單例模式

class Singleton{ 
	static std::auto_ptr m_pInstance; 
protected: //拒絕任何形式的手動創建 
	Singleton(){} 
public: 
	~Singleton(){} 
	//返回單件實例 
	static Singleton* Instance()
	{ 
		if(!m_pInstance.get())
		{
			m_pInstance = std::auto_ptr(new Singleton()); 
		} 
		return m_pInstance.get(); 
	} 
};
//以上是一個完整的單例實現,然而這個實現不是線程安全的,在多線程環境下,需要使用線程互斥獲取單件實例,一個優雅的方法見《double-check》 
//需要多個單件子類,可做下面的宏定義
#define DEFINE_SINGLETON(cls)\ 
private:\ 
			static std::auto_ptr m_pInstance;\
 protected:\ 
		   cls(){}\ 
public:\ ~cls(){}\ 
	   static cls* Instance(){\ 
	   if(!m_pInstance.get()){\ 
		   m_pInstance = std::auto_ptr(new cls());\ 
	   }\ return m_pInstance.get();\ 
		}#define IMPLEMENT_SINGLETON(cls) \ 
		std::auto_ptr cls::m_pInstance(NULL); 
//這樣實現一個單例類如下: 
		//.h文件
		class Single {
			DEFINE_SINGLETON(Single);
		public://your interfaces here...
		};
		//.cpp文件
		IMPLEMENT_SINGLETON(Single); 
		//使用: 
		Single* pSingle = Single::Instance();


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章