Singleton模式是一種非常簡單的設計模式,這種模式很常用也很容易被濫用。當你設計應用程序的時候,經常會遇到某些對象在整個程序的生命周期應該僅有一個實例的情況,比如File System,Graphic System,Logging Utility,這時候就可以用到Singleton模式。Singleton模式在GOF中描述如下:
Ensure a class only has one instance, and provide a global point of access to it.
Singleton模式的定義很簡單,實現也有N多種,但是卻很難找到一個稱得上“完美”的。實現一個完美的Singleton比想象中要難的多,下面探索性的來實現一個非完美的。
1.典型實現
在C++中,Singleton模式的典型實現如下:
1 // Header file Singleton.h
2 class Singleton {
3 public :
4 static Singleton& Instance() { // Unique point of access
5 if (0 == _instance)
6 _instance = new Singleton();
7 return * _instance;
8 }
9 void DoSomething();
10 private :
11 Singleton(); // Prevent clients from creating a new Singleton
12 ~Singleton(); // Prevent clients from deleting a Singleton
13 Singleton(const Singleton&); // Prevent clients from copying a Singleton
14 Singleton& operator=(const Singleton& );
15 private :
16 static Singleton *_instance; // The one and only instance
17 };
18
19 // Implementation file Singleton.cpp
20 Singleton* Singleton::_instance = 0;
通過將Singleton的構造函數設為private可以禁止客戶代碼直接創建Singleton對象,除此之外,Singleton的copy constructor和copy assignment operator都為private且僅有聲明沒有實現,禁止了客戶代碼拷貝Singleton對象。唯一可以創建Singleton對象的是Singleton自己的靜態成員函數Instance,這樣就在編譯器保證了Singleton實例的唯一性。上面這些是在C++中實現Singleton模式最基本的要點。
Instance方法保證只有在第一次調用時才會生成Singleton對象,以后的調用只是簡單返回唯一的已存在的實例。Instance方法實際上實現的是懶惰初始化(lazy initialize),如果程序中根本沒有用到Singleton對象,也就根本不會產生Singleton的實例,這在Singleton對象很少使用且創建Singleton對象開銷比較大的情況下特別有用。
客戶代碼現在可以這樣使用Singleton:
1 Singleton &s = Singleton::Instance();
2 s.DoSomething();
還需要說明的是Singleton的析構函數,析構函數也為private可以禁止客戶寫出如下代碼。如果某個客戶寫出了如下代碼,隨后的對Singleton的訪問就會導致為定義行為,因為Singleton對象已經不存在。
1 Singleton *p = & Singleton::Instance();
2 delete p;
2.引入smart pointer
上面的實現算是一個好的實現嗎?當然不是,或許連一個正確的實現都算不上。如果你想湊合,當然沒問題,上面的代碼大多數情況下可以工作的很好。也許你已經注意到了一些問題,比如說在上面的代碼中只有new沒有delete。是的,你說會發生memory leak對吧,其實memory leak都不是主要的問題,所有的現代操作系統在進程結束的時候都會對內存很好的進行回收。比memory leak更值得讓人擔憂的是resource leak,如果Singleton在構造函數中請求了某些資源:網絡連接,文件句柄,數據庫連接等。這些資源將得不到釋放。
唯一修正resource leak的方法就是在程序結束的時候delete _instance。當然了,用smart pointer再好不過,在這里用auto_ptr就可以滿足需要了(如果你還不知道smart_ptr是什么,花點時間熟悉C++標準庫吧),修改后的代碼如下:
1 // Header file Singleton.h
2 class Singleton {
3 public :
4 static Singleton& Instance() { // Unique point of access
5 if (0 == _instance.get())
6 _instance.reset(new Singleton());
7 return * (_instance.get());
8 }
9 void DoSomething(){}
10 private :
11 Singleton(){} // Prevent clients from creating a new Singleton
12 ~Singleton(){} // Prevent clients from deleting a Singleton
13 Singleton(const Singleton&); // Prevent clients from copying a Singleton
14 Singleton& operator=(const Singleton& );
15 private :
16 friend auto_ptr<Singleton> ;
17 static auto_ptr<Singleton> _instance; // The one and only instance
18 };
19
20 // Implementation file Singleton.cpp
21 auto_ptr<Singleton> Singleton::_instance;
3.用atexit替換smart pointer
C++并沒有規定不同編譯單元(translation unit,簡單說就是一個可編譯的cpp文件)中static對象的初始化順序。如果一個程序中有多個Singleton對象,那么這些Singleton對象的析構順序也將是任意的。很顯然,當多個Singleton對象有依賴關系時,smart pointer根本無法保證Singleton的析構順序。
msdn中對atexit描述如下:
The atexit function is passed the address of a function (func) to be called when the program terminates normally. Successive calls to atexit create a register of functions that are executed in last-in, first-out (LIFO) order. The functions passed to atexit cannot take parameters. atexit use the heap to hold the register of functions. Thus, the number of functions that can be registered is limited only by heap memory.
需要說明的是atexit并不比smart pointer好多少,LIFO的保證對于有復雜依賴關系的多個Singleton依然束手無力,但是用atexit替換smart pointer卻是必須的,它是設計完美Singleton的基礎。
#如果你疑惑atexit為什么還是不行,請考慮下面的情況:
NOTE:下面的情況在Modern C++ Design中叫做KDL(Keyboard,Display,Log)problem。
某個程序中使用了如下3個Singleton:Keyboard,Display,Log。Keyboard和Display分別對應于計算機的鍵盤和顯示器,Log用來記錄錯誤信息。假設當Keyboard和Display的構造函數和析構函數出現錯誤時會調用Log記錄錯誤信息,并且構造和析構導致的任何錯誤都會終止程序。
在程序啟動時,如果Keyboard構造成功,Display構造失敗,很顯然在Display的構造函數中將會構造Log而且失敗信息會被Log記錄,根據假設這時候程序準備退出,atexit注冊的函數將會按LIFO的順序被調用。因為Keyboard先于Log構造,所以Log先于Keyboard析構,但是當由于某種原因Keyboard在析構時失敗,想要調用Log記錄錯誤信息時,Log早已被銷毀,則Log::Instance()將會導致未定義行為。
#atexit的嚴重問題:
從上面的例子可以看出,atexit和smart pointer相比僅僅是有LIFO的保證而已,這樣的保證貌似也不怎么有效,因為atexit跟smart pointer一樣也無法解決KDL probleam。
atexit由于LIFO帶來了另外的問題,看下面的代碼:
1 #include <cstdlib>
2 void Bar() {
3 ...
4 }
5 void Foo() {
6 std::atexit(Bar);
7 }
8 int main() {
9 std::atexit(Foo);
10 return 0 ;
11 }
上面的小段代碼用atexit注冊了Foo,Foo調用了std::atexit(Bar)。當程序退出時,根據atexit的LIFO保證,Bar在Foo之后注冊,因此Bar應該在Foo之前調用,但是當Bar注冊的時候Foo已經調用了,Bar根本就沒有機會能夠在Foo之前調用。這明顯自相矛盾對吧,沒辦法,C++標準好像忽視了這一點,因此如果類似代碼被調用,肯定不會有什么好的結果,好一點是resource leak,差一點估計程序就崩潰了!!!
atexit的這個問題跟Singleton有關系嗎?當然有,如果在一個Singleton的析構函數中調用atexit就會出現上述問題。即在KDL problem中,如果Keyboard和Display都構造成功,當Keyboard或Display任意一個析構失敗時,Keyboard或Display在析構函數中會構造Log,Log的構造函數會間接調用atexit。oops!!!,可怕的未定義行為。
看到這里你一定對atexit相當失望,貌似它帶來的好處多于壞處。但是請你相信,如果適當設計,atexit在后面的Singleton改造中會起到很重要的作用。
用atexit后的代碼:
1 // Header file Singleton.h
2 class Singleton {
3 public :
4 static Singleton& Instance() { // Unique point of access
5 if (0 == _instance) {
6 _instance = new Singleton();
7 atexit(Destroy); // Register Destroy function
8 }
9 return * _instance;
10 }
11 void DoSomething(){}
12 private :
13 static void Destroy() { // Destroy the only instance
14 if ( _instance != 0 ) {
15 delete _instance;
16 _instance = 0 ;
17 }
18 }
19 Singleton(){} // Prevent clients from creating a new Singleton
20 ~Singleton(){} // Prevent clients from deleting a Singleton
21 Singleton(const Singleton&); // Prevent clients from copying a Singleton
22 Singleton& operator=(const Singleton& );
23 private :
24 static Singleton *_instance; // The one and only instance
25 };
26
27 // Implementation file Singleton.cpp
28 Singleton* Singleton::_instance = 0;
你有沒有仔細考慮過Destroy中的_instance = 0;這一行代碼,上述代碼實際上實現的是
不死鳥模式(The Phoenix Singleton),所謂不死鳥,就跟一輝一樣可以死而復生。上面的代碼可以解決本文最早提出的
KDL problem,即如果
Keyboard析構失敗,雖然
Log已經析構,但是由于Destroy中的_instance = 0;這一行代碼,Log::Instance()將會創建一個新的
Log對象,程序將會表現良好。當然了,
Phoenix Singleton僅能用于無狀態的Singleton,如果
Log需要保存某些狀態,
Phoenix Singleton也不會帶來任何好處。你當然可以用某些方法維持
Phoenix Singleton的狀態,但是在做之前先想想看是否值得,維持狀態可能會使Singleton變得特別復雜。
上面的
Phoenix Singleton已經可以滿足大部分需要,如果你的Singleton沒有涉及到多線程,多個Singleton之間也沒有依賴關系,你大可以放心使用。但是如果你用到多線程,或者你的Singleton關系如
KDL般復雜,或者你覺得對每一個Singleton都敲同樣的代碼讓你厭煩。在后面幾篇會有一個
多線程安全的,能夠
解決多個Singleton依賴關系的,
基于模板的Singleton實現。