标签:
1. 单例模式 (多线程下)
a. 饿汉式
1 template<class T> 2 class Singleton { 3 public: 4 static T* get_instance() { 5 if( _instance == NULL ) { 6 pthread_mutex_lock(&_mutex); 7 if( _instance == NULL ) { 8 _instance = new T; 9 } 10 pthread_mutex_unlock(&_mutex); 11 } 12 return _instance; 13 } 14 15 protected: 16 Singleton(){} 17 virtual ~Singleton() { 18 if(_instance) { 19 T* t = _instance; 20 _instance = NULL; 21 delete t; 22 } 23 } 24 25 private: 26 static T* _instance; 27 static pthread_mutex_t _mutex; 28 }; 29 30 template<class T> T* Singleton<T>::_instance = NULL; 31 template<class T> pthread_mutex_t Singleton<T>::_mutex = PTHREAD_MUTEX_INITIALIZER;
b. 懒汉式
1 class Singleton { 2 public: 3 static const Singleton* get_instance() { 4 return _instance; 5 } 6 private: 7 Singleton(){} 8 ~Singleton() { 9 if(_instance) { 10 delete _instance; 11 _instance = NULL; 12 } 13 } 14 15 static const Singleton* _instance; 16 }; 17 const Singleton* Singleton::_instance = new Singleton();
标签:
原文地址:http://www.cnblogs.com/liyangguang1988/p/5416792.html