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