码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式

时间:2016-04-21 15:08:06      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

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;
View Code

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();
View Code

 

设计模式

标签:

原文地址:http://www.cnblogs.com/liyangguang1988/p/5416792.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!