C++ Singleton
File:singleton.hpp
1 #ifndef __SINGLETON_HPP_ 2 #define __SINGLETON_HPP_ 3 4 template <class T> 5 class Singleton 6 { 7 public: 8 static T* Instance() { 9 if(!m_pInstance) m_pInstance = new T; 10 assert(m_pInstance !=NULL); 11 return m_pInstance; 12 } 13 protected: 14 Singleton(); 15 ~Singleton(); 16 private: 17 Singleton(Singleton const&); 18 Singleton& operator=(Singleton const&); 19 static T* m_pInstance; 20 }; 21 22 template <class T> T* Singleton<T>::m_pInstance=NULL; 23 24 #endif
Usage:
1 #include "singleton.hpp" 2 3 class Logger 4 { 5 public: 6 Logger() {}; 7 ~Logger() {}; 8 bool openLogFile(string); 9 void writeToLogFile(string); 10 bool closeLogFile(string); 11 private: 12 ... 13 ... 14 }; 15 16 bool Logger::openLogFile(std::string) 17 { 18 ... 19 ... 20 } 21 22 ... 23 ... 24 25 typedef Singleton<Logger> LoggerSingleton; // Global declaration 26 27 main() 28 { 29 ... 30 31 LoggerSingleton::Instance()->openLogFile("logFile.txt"); 32 33 ... 34 }
来自:http://www.yolinux.com/TUTORIALS/C++Singleton.html