保证一个类仅有一个实例,并提供一个访问它的全局访问方法.
main.cc:
#include "singleton.h" #include <iostream> #include <windows.h> #include <stdio.h> using namespace std; int main(){ //this will cause compile error,because singleton construct is protected! //Singleton *singleton = new singleton(); Singleton *singleton_p1 = Singleton::GetInstance(); Singleton *singleton_p2 = Singleton::GetInstance(); printf("singleton_p1:%p\nsingleton_p2:%p\nsingletons are the same!\n",singleton_p1,singleton_p2); //clear delete singleton_p1; system("Pause"); return 0; }Singleton:
//singleton.h #ifndef HELENDP_SOURCE_SINGLETON_H_ #define HELENDP_SOURCE_SINGLETON_H_ class Singleton{ public: ~Singleton(); static Singleton* GetInstance(); protected: Singleton(); private: static Singleton *singleton_; }; #endif //singleton.cc: #include "singleton.h" #include <iostream> using namespace std; #include <stdio.h> //static member need to define for allocated memory , otherwise will cause compile error! Singleton * Singleton::singleton_ = NULL; Singleton::Singleton(){ cout << "Singleton construct!" << endl; } Singleton::~Singleton(){ cout << "Singleton destruct!" << endl; } Singleton* Singleton::GetInstance(){ if(NULL == singleton_){ singleton_ = new Singleton(); } return singleton_; }代码和UML图(EA)工程文件,最后会整理打包上传.