C++單例模式應(yīng)用實例
本文實例講述了C++單例模式及其相關(guān)應(yīng)用方法,分享給大家供大家參考。具體方法分析如下:
定義:
一個類有且僅有一個實例,并且提供一個訪問它的全局訪問點。
要點:
1、類只能有一個實例;
2、必須自行創(chuàng)建此實例;
3、必須自行向整個系統(tǒng)提供此實例。
實現(xiàn)一:單例模式結(jié)構(gòu)代碼
singleton.h文件代碼如下:
#ifndef _SINGLETON_H_ #define _SINGLETON_H_ class Singleton { public: static Singleton* GetInstance(); protected: Singleton(); private: static Singleton *_instance; }; #endif
singleton.cpp文件代碼如下:
#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; }
實現(xiàn)二:打印機(jī)實例
singleton.h文件代碼如下:
#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文件代碼如下:
#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 -Wall all: make singleton singleton:singleton.o\ main.o ${CC} -o singleton main.o singleton.o clean: rm -rf singleton rm -f *.o .cpp.o: $(CC) $(CFLAGS) -c -o $*.o $<
運(yùn)行效果如下圖所示:
可以看到,對打印順序count的計數(shù)是連續(xù)的,系統(tǒng)中只有一個打印設(shè)備。
希望本文所述對大家的C++程序設(shè)計有所幫助。
相關(guān)文章
用C實現(xiàn)PHP擴(kuò)展 Image_Tool 圖片常用處理工具類的使用
該擴(kuò)展是基于ImageMagick基礎(chǔ)實現(xiàn)的,圖片操作調(diào)用的是ImageMagick API2013-04-04Inline Hook(ring3)的簡單C++實現(xiàn)方法
這篇文章主要介紹了Inline Hook(ring3)的簡單C++實現(xiàn)方法,需要的朋友可以參考下2014-08-08C++不使用變量求字符串長度strlen函數(shù)的實現(xiàn)方法
這篇文章主要介紹了C++不使用變量求字符串長度strlen函數(shù)的實現(xiàn)方法,實例分析了strlen函數(shù)的實現(xiàn)原理與不使用變量求字符串長度的實現(xiàn)技巧,需要的朋友可以參考下2015-06-06如何實現(xiàn)socket網(wǎng)絡(luò)編程的多線程
首先,學(xué)好計算機(jī)網(wǎng)絡(luò)知識真的很重要。雖然,學(xué)不好不會影響理解下面這個關(guān)于宏觀講解,但是,學(xué)好了可以自己打漁吃,學(xué)不好就只能知道眼前有魚吃卻打不到漁。在Java中網(wǎng)絡(luò)程序有2種協(xié)議:TCP和UDP,下面可以和小編一起學(xué)習(xí)下2019-05-05