單例模式c++實現方法總結
阿新 • • 發佈:2019-02-03
一 單例模式介紹
單例模式約束了類的例項化,只允許類建立一個物件。
在用程式碼實現單例模式之前,先看看單例模式的類結構:
特點:
1. 類的建構函式外界不可訪問.
2. 提供了建立物件的介面.
二 單例模式C++實現
1. 實現方法一(只作為樣例,不推薦使用)
// .h檔案 class SimpleSingleton { public: ~SimpleSingleton(){} // 因為外界負責delete,所以須注意解構函式訪問許可權 static SimpleSingleton* Instance() { if(!instance_) // 執行緒不安全,這裡需要同步 instance_ = new SimpleSingleton; return instance_; } protected: SimpleSingleton(){} static SimpleSingleton* instance_; }; // cpp檔案 SimpleSingleton* SimpleSingleton::instance_ = 0;
該方法是簡陋的單例模式實現方式,缺點是:
該類只負責類物件的建立,沒有負責銷燬,還得程式設計師負責在合適的時機銷燬,所以不推薦使用該方法。
2 實現方法二(智慧指標方式)
// .h檔案 class PtrSingleton { public: ~PtrSingleton(){} // 必須為public, 智慧指標負責析構 static scoped_ptr<PtrSingleton>& Instance() { if(NULL == instance_.get()) // 執行緒不安全,這裡需要同步 instance_.reset(new PtrSingleton); return instance_; } // other members protected: PtrSingleton(){} static scoped_ptr<PtrSingleton> instance_; }; // .cpp檔案 scoped_ptr<PtrSingleton> PtrSingleton::instance_;
該方法特點:
1) 避免了手動析構.
2) 值得注意的是例項化介面返回型別不是物件指標、值、引用,而是智慧指標.
3) 但在實際使用中要考慮到多執行緒環境下的使用,Instance介面是執行緒不安全的,需要同步一下,本篇重點講單例模式,程式碼樣例中就不做執行緒同步了.
3 實現方法三(簡單方式)
// .cpp檔案 class Singleton { public: ~Singleton(){} static Singleton& Instance(){return instance_;} // testing member protected: Singleton(){} Singleton(const Singleton&); Singleton& operator=(const Singleton&); private: static Singleton instance_; }; // .cpp檔案 Singleton Singleton::instance_;
這種方法實現起來簡單,用起來方便,安全。
三 單例模式模版實現
// .h檔案
template <typename T>
class TSingleton
{
public:
virtual ~TSingleton(){} // 必須為public, 智慧指標負責析構
static scoped_ptr<T>& Instance()
{
if(NULL == instance_.get()) // 執行緒不安全,這裡需要同步
instance_.reset(new T);
return instance_;
}
protected:
TSingleton(){}
TSingleton(const TSingleton<T>&);
TSingleton<T>& operator=(const TSingleton<T>);
static scoped_ptr<T> instance_;
};
template<typename T>
scoped_ptr<T> TSingleton<T>::instance_;
單例模版的應用例項
class Derived : public TSingleton<Derived>
{
public:
// other members
protected:
Derived(){}
~Derived(){}
};
(完)