目的
設計單例模式的目的是為了解決兩個問題:
- 保證一個類只有一個實例
這種需求是需要控制某些資源的共享權限,比如文件資源、數據庫資源。
- 為該實例提供一個全局訪問節點
相較于通過全局變量保存重要的共享對象,通過一個封裝的類對象,通過提供全局訪問節點,不僅可以保護全局對象不被覆蓋,同時能夠將分散的代碼封裝在一個類中。
實現方式
- 將默認構造函數設為私有,防止其他對象使用單例的new運算符;
- 新建靜態構造方法作為構造單例對象的構造方法,該方法調用私有構造函數創建單例對象并保存在一個靜態變量中,后續所有對該靜態方法的調用都會返回該緩存對象。
具體的實現方式又分為餓漢模式和懶漢模式。餓漢模式即在初始階段就主動進行實例化,即存儲單例對象的靜態變量在初始化階段即通過new運算符構建一個單例對象,無論該單例是否有人使用;懶漢模式即在靜態構造方法中構造單例對象,且只有在單例對象為空(nullptr)時才會主動構建對象。
但懶漢模式在多線程情況下其實是有缺陷的,如果并發請求,同時調用靜態構造方法,則存儲單例對象的靜態變量會被多次復制,違背的單例的理念。這種情況下用鎖來保證同步。但是同步鎖使用不當不僅會帶來不必要的風險,同時加鎖、解鎖也是對資源的浪費,因此餓漢模式反倒是一種更好的方式,如果單例遲早要被實例化,那么延遲加載的意義就不大。懶漢模式實現代碼如下:
class Singleton
{
private:static Singleton* pinstance_;static std::mutex mutex_;protected:Singleton(const std::string value) : value_(value){}~Singleton() {}std::string value_;public:Singleton(Singleton& other) = delete;void operator=(const Singleton&) = delete;static Singleton* GetInstance(const std::string& value);std::string value() const {return value_;}
};Singleton* Singleton::pinstance_{ nullptr };
std::mutex Singleton::mutex_;Singleton* Singleton::GetInstance(const std::string& value)
{if (pinstance_ == nullptr){std::lock_guard<std::mutex> lock(mutex_);if (pinstance_ == nullptr){pinstance_ = new Singleton(value);}return pinstance_;}
}void ThreadFoo() {// Following code emulates slow initialization.std::this_thread::sleep_for(std::chrono::milliseconds(1000));Singleton* singleton = Singleton::GetInstance("FOO");std::cout << singleton->value() << "\n";
}void ThreadBar() {// Following code emulates slow initialization.std::this_thread::sleep_for(std::chrono::milliseconds(1000));Singleton* singleton = Singleton::GetInstance("BAR");std::cout << singleton->value() << "\n";
}int main()
{std::cout << "If you see the same value, then singleton was reused (yay!\n" <<"If you see different values, then 2 singletons were created (booo!!)\n\n" <<"RESULT:\n";std::thread t1(ThreadFoo);std::thread t2(ThreadBar);t1.join();t2.join();return 0;
}