这里展示的是最简单的Singleton(单例模式),不考虑多线程,因此也就没有考虑线程安全和加锁的话题了。
Singleton类的定义
//Singleton Definition class Singleton{ public: static Singleton* getInstance(); private: Singleton(){ std::cout<<"the first time constructor is shown"<<std::endl; }; static Singleton* instance; }; //Xcode中要加上这句话才能编译通过,要给全局变量和类的静态变量初始化为0才能在Xcode中编译通过。 Singleton* Singleton::instance=NULL; Singleton * Singleton::getInstance() { if (!instance) { instance = new Singleton(); }; return instance; };
main函数中对Singleton类的使用
int main(int argc, const char * argv[]) { Singleton* p1=Singleton::getInstance(); Singleton* p2=Singleton::getInstance(); if(p1==p2) std::cout << "Hello, World!\n"; return 0; }
输出如下:
the first time constructor is shown Hello, World! Program ended with exit code: 0