Posted on 2008-03-01 22:01
Wang Jinbo 閱讀(2117)
評論(5) 編輯 收藏 引用 所屬分類:
設計模式
對于某些用途的類,必須確保在程序運行過程中最多只有一個實例。單件模式很適合這種場合。
單件模式實現(xiàn)的技巧是將構造函數(shù)私有化,這樣就禁止了直接定義對象變量和用new生成對象。但將構造函數(shù)設為私有的話,又如何去生成那個唯一的對象呢?廢話少說,先貼代碼。
class Singleton{
private:
Singleton(){
// more code
}
static Singleton *thisInstance;
// more code
public:
static Singleton *getInstance();
// more code
};
Singleton *Singleton::thisInstance=NULL;
Singleton *Singleton::getInstance(){
if (thisInstance==NULL)
thisInstance=new Singleton();
return thisInstance;
}
如此一來,要取得Singleton的實例,只能用getInstance函數(shù)。getInstance函數(shù)必須是靜態(tài)(Static)的,這樣才能在還沒有實例的時候使用這個函數(shù)。而getInstance又是Singleton類里的函數(shù),當然是可以在其中使用new來生成對象了。所以說雖然將類的構造函數(shù)私有化了,但構造函數(shù)本身還是有意義的,它會在構建第一個,也是唯一一個實例的時候執(zhí)行。同時,保證了不會出現(xiàn)多于一個的實例。