設計模式筆記:單例模式(C++代碼)

來源:互聯網
上載者:User

定義:
一個類有且僅有一個執行個體,並且提供一個訪問它的全域訪問點。
要點:
1、類只能有一個執行個體;
2、必須自行建立此執行個體;
3、必須自行向整個系統提供此執行個體。

實現一:單例模式結構代碼

singleton.h:

View Code

#ifndef _SINGLETON_H_#define _SINGLETON_H_class Singleton{public:    static Singleton* GetInstance();protected:    Singleton();private:    static Singleton *_instance;};#endif

singleton.cpp:

View Code

#include "singleton.h"#include <iostream>using namespace std;Singleton* Singleton::_instance = 0;Singleton::Singleton(){    cout<<"create Singleton ..."<<endl;}Singleton* Singleton::GetInstance(){    if(0 == _instance)    {        _instance = new Singleton();    }    else    {        cout<<"already exist"<<endl;    }    return _instance;}

main.cpp:

#include "singleton.h"int main(){    Singleton *t = Singleton::GetInstance();    t->GetInstance();    return 0;}

實現二:印表機執行個體

singleton.h:

View Code

#ifndef _SINGLETON_H_#define _SINGLETON_H_class Singleton{public:    static Singleton* GetInstance();    void printSomething(const char* str2Print);protected:    Singleton();private:    static Singleton *_instance;    int count;};#endif

singleton.cpp:

View Code

#include "singleton.h"#include <iostream>using namespace std;Singleton* Singleton::_instance = 0;Singleton::Singleton(){    cout<<"create Singleton ..."<<endl;    count=0;}Singleton* Singleton::GetInstance(){    if(0 == _instance)    {        _instance = new Singleton();    }    else    {        cout<<"Instance already exist"<<endl;    }    return _instance;}void Singleton::printSomething(const char* str2Print){    cout<<"printer is now working , the sequence : "<<++count<<endl;    cout<<str2Print<<endl;    cout<<"done\n"<<endl;}

main.cpp:

#include "singleton.h"int main(){    Singleton *t1 = Singleton::GetInstance();    t1->GetInstance();    t1->printSomething("t1");    Singleton *t2 = Singleton::GetInstance();    t2->printSomething("t2");    return 0;}

Makefile檔案:

CC=g++CFLAGS = -g -O2 -Wallall:    make singletonsingleton:singleton.o\    main.o        ${CC} -o singleton main.o singleton.oclean:    rm -rf singleton    rm -f *.o.cpp.o:    $(CC) $(CFLAGS) -c -o $*.o $<

運行效果:

可以看到,對列印順序count的計數是連續的,系統中只有一個列印裝置。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.