定義:
一個類有且僅有一個執行個體,並且提供一個訪問它的全域訪問點。
要點:
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的計數是連續的,系統中只有一個列印裝置。