Singleton.h
// // Singleton.h // Singleton // // Created by Cheney Shen on 11-2-20. // Copyright 2011年 __MyCompanyName__. All rights reserved. // #ifndef _SINGLETON_H_ #define _SINGLETON_H_ #include <iostream> using namespace std; class Singleton { public: static Singleton* Instance(); protected: Singleton(); private: static Singleton* _instance; }; #endif //~_SINGLETON_H_
Singleton.cpp
// // Singleton.cpp // Singleton // // Created by Cheney Shen on 11-2-20. // Copyright 2011年 __MyCompanyName__. All rights reserved. // #include "Singleton.h" #include <iostream> using namespace std; Singleton* Singleton::_instance = 0; Singleton::Singleton() { cout<<"Singleton..."<<endl; } Singleton* Singleton::Instance() { if(_instance==0){ _instance = new Singleton(); } return _instance; }
main.cpp
// // main.cpp // Singleton // // Created by Cheney Shen on 11-2-20. // Copyright 2011年 __MyCompanyName__. All rights reserved. // #include "Singleton.h" #include <iostream> using namespace std; int main (int argc, const char * argv[]) { Singleton* sgn = Singleton::Instance(); return 0; }