Singleton模式Linux下的C++实现


Singleton模式是最常用的设计之一,最近结合自己的实际应用,把Singleton作为模板抽象出来(线程安全),权当抛砖引用,欢迎大家提出批评意见,互相交流。下面为源码,已经编译运行过。

Singleton 模板类

  1. #ifndef _Singleton_h_   
  2. #define _Singleton_h_   
  3.   
  4. #include <pthread.h>   
  5. class Mutex  
  6. {  
  7. public:  
  8.     Mutex()  
  9.     {  
  10.         pthread_mutex_init(&m_lock,NULL);  
  11.     }  
  12.   
  13.     ~Mutex()  
  14.     {  
  15.         pthread_mutex_destroy(&m_lock);  
  16.     }  
  17.   
  18.     void Lock()  
  19.     {  
  20.         pthread_mutex_lock(&m_lock);  
  21.     }  
  22.   
  23.     void UnLock()  
  24.     {  
  25.         pthread_mutex_unlock(&m_lock);  
  26.     }  
  27.   
  28. private:  
  29.     pthread_mutex_t m_lock;  
  30. };  
  31.   
  32. template<class T>  
  33. class Singleton  
  34. {  
  35. public:  
  36.     static T*    GetInstance();  
  37.         static void  Destroy();  
  38. private:  
  39.     static T*    m_pInstance;  
  40.         static Mutex m_mutex;  
  41. };  
  42.   
  43. template<class T>  
  44. T* Singleton<T>::m_pInstance = 0;  
  45.   
  46. template<class T>  
  47. Mutex Singleton<T>::m_mutex;  
  48.   
  49. template<class T>  
  50. T* Singleton<T>::GetInstance()  
  51. {  
  52.     if (m_pInstance)  
  53.     {  
  54.         return m_pInstance;  
  55.     }  
  56.     m_mutex.Lock();  
  57.     if (NULL == m_pInstance)  
  58.     {  
  59.         m_pInstance = new T;  
  60.     }  
  61.     m_mutex.UnLock();  
  62.     return m_pInstance;  
  63. }  
  64.   
  65. template<class T>  
  66. void Singleton<T>::Destroy()  
  67. {  
  68.     if (m_pInstance)  
  69.     {  
  70.         delete m_pInstance;  
  71.         m_pInstance= NULL;  
  72.     }  
  73. }  
  74.   
  75. #endif  
  • 1
  • 2
  • 下一页

相关内容