书上给的是C#实现,自己写几个C++实现:
1. 基本版,适用于单线程
1 class Singleton 2 { 3 public: 4 static Singleton * Instance(); 5 static void Destroy(); 6 protected: 7 Singleton(){} 8 private: 9 static Singleton * m_pInstance; 10 }; 11 12 Singleton * Singleton::m_pInstance = NULL; 13 14 Singleton * Singleton::Instance() 15 { 16 if (m_pInstance == NULL) 17 m_pInstance = new Singleton; 18 return m_pInstance; 19 } 20 21 void Singleton::Destroy() 22 { 23 delete m_pInstance; 24 }
2. 多线程,使用加锁机制
利用winAPI中的加锁
1 #include <Windows.h> 2 3 class Locker 4 { 5 protected: 6 friend class Singleton; 7 CRITICAL_SECTION cs; 8 9 public: 10 Locker(){ 11 ::InitializeCriticalSection(&cs); 12 } 13 void lock(){ 14 ::EnterCriticalSection(&cs); 15 } 16 void unlock(){ 17 ::LeaveCriticalSection(&cs); 18 } 19 ~Locker(){ 20 ::DeleteCriticalSection(&cs); 21 } 22 }; 23 24 class Singleton 25 { 26 public: 27 static Singleton * Instance(); 28 static void Destroy(); 29 protected: 30 Singleton(){} 31 private: 32 static Singleton * m_pInstance; 33 }; 34 35 Singleton * Singleton::m_pInstance = NULL; 36 37 Singleton * Singleton::Instance() 38 { 39 Locker *lock = new Locker; 40 lock->lock(); 41 if (m_pInstance == NULL) 42 m_pInstance = new Singleton; 43 lock->unlock(); 44 return m_pInstance; 45 } 46 47 void Singleton::Destroy() 48 { 49 delete m_pInstance; 50 }
3. 模版实现
1 class Singleton 2 { 3 public: 4 static T * Instance(); 5 static void Destroy(); 6 protected: 7 Singleton(){} 8 private: 9 static T * m_pInstance; 10 }; 11 12 template <typename T> 13 T * Singleton<T>::m_pInstance = NULL; 14 15 template <typename T> 16 T * Singleton<T>::Instance() 17 { 18 if (m_pInstance == NULL) 19 m_pInstance = new T; 20 return m_pInstance; 21 } 22 23 template <typename T> 24 void Singleton<T>::Destroy() 25 { 26 delete m_pInstance; 27 }
参考资料:
http://blog.csdn.net/a342374071/article/details/18270643/
http://www.cnblogs.com/liyuan989/p/4264889.html