- 在面試的時候,面試官提到了單例模式。我沒有接觸過,但也瞭解。這讓面試官對我的影響有所失望,回來之後就買了《設計模式-可複用物件導向軟體的基礎》。翻開單例模式,發現用C++實現的單例模式還真的有點水平。
- 單例模式指在我們的程式中有一個組件,它的類只有唯一的一個對象,也不可以建立更多的對象。這種模式就是單例模式。
實現如下:上面的單例模式的實現要求我們如下方式使用類Singleton
class Singleton{public:static Singleton* Instance(); void DoSomeThing();protected:Singleton():totle(0.0){};private:static Singleton* instance_;};Singleton* Singleton::instance_=0;Singleton* Singleton::Instance(){if (instance_==0){instance_=new Singleton();}return instance_;}
我們可能像這樣使用這個類的對象Singleton* p=Singleton::Instance();p->DoSomeThing();
由於它沒有共用的建構函式,所以只能使用Instance方法擷取,而這個方法總是判斷是否已經建立了唯一的對象,如果已經建立,就直接使用。否則就建立一個。其唯一的建構函式不是public的,但可以被類內部調用,並且初始化了用來標記建立對象個數的instance_指標。
有時候我的程式需要一個用來方便計時的東西,我就用單例模式實現了,它可以告訴你在每兩次調用之間花了多長時間,而且還隨時告訴你從一開始運行到現在一共用了多少時間。另外它還支援,每次顯示時間的時候列印一些說明性的文字,而這些只需要在一次調用就可以完成。是不是很棒呢?其實現如下:
class SingletonTimer{public:static SingletonTimer* Instance();void print(const string& out) {double temp=timer_.elapsed();totle+=temp;cout<<out<<" 用時:"<<temp<<"秒,目前共用時:"<<totle<<"秒"<<endl;timer_.restart();}protected:SingletonTimer():totle(0.0){};private:static SingletonTimer* instance_;timer timer_;double totle;};SingletonTimer* SingletonTimer::instance_=0;SingletonTimer* SingletonTimer::Instance(){if (instance_==0){instance_=new SingletonTimer();}return instance_;}