单例模式(C++)
#include <iostream> #include <string> using namespace std; class singleton { private: singleton(){}; //构造函数为private,禁止客户new出实例 virtual ~singleton() { if (instance!=NULL) delete instance; }; static singleton *instance; public: static singleton *GetInstance() { if (instance==NULL) { instance = new singleton; } return instance; } }; singleton *singleton::instance=NULL; int main() { singleton *s1=singleton::GetInstance(); singleton *s2=singleton::GetInstance(); if (s1==s2) { cout<<"同一个实例"<<endl; } system("pause"); return 0; }