單例模式(定製一個計時器)

來源:互聯網
上載者:User
  1. 在面試的時候,面試官提到了單例模式。我沒有接觸過,但也瞭解。這讓面試官對我的影響有所失望,回來之後就買了《設計模式-可複用物件導向軟體的基礎》。翻開單例模式,發現用C++實現的單例模式還真的有點水平。
  2. 單例模式指在我們的程式中有一個組件,它的類只有唯一的一個對象,也不可以建立更多的對象。這種模式就是單例模式。

實現如下:上面的單例模式的實現要求我們如下方式使用類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_;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.