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