C++實現單例模式

 

  1. //Singleton.h  
  2. #ifndef _SINGLETON_H_  
  3. #define _SINGLETON_H_  
  4. #include <iostream>  
  5. #include <pthread.h>  
  6. using namespace std;  
  7.  
  8. class locker    
  9. {    
  10. public:    
  11.     inline locker(){        pthread_mutex_init(&mutex,NULL);}    
  12.     inline ~locker(){       pthread_mutex_destroy(&mutex);}    
  13.     inline void lock(){     pthread_mutex_lock(&mutex);}    
  14.     inline void unlock(){   pthread_mutex_unlock(&mutex);}    
  15. private:    
  16.     pthread_mutex_t mutex;    
  17. };    
  18. class Singleton  
  19. {  
  20. public:  
  21. static Singleton* Instance();  
  22.  
  23. private:  
  24.   Singleton();  
  25.   static Singleton * m_pInstance;  
  26.  class Garbo//刪除Singleton實例的對象  
  27.     {  
  28.     public:  
  29.         ~Garbo()  
  30.         {  
  31.             if(Singleton::m_pInstance)  
  32.             {  
  33.                 delete Singleton::m_pInstance;  
  34.             }  
  35.         }  
  36.     };  
  37.     static Garbo gb;//在程序結束時,系統會調用它的析構函數  
  38.  
  39. };  
  40. #endif //~_SINGLETON_H_  
  41.  
  42.  
  43.  
  44.  
  45. //Singleton.cpp  
  46. #include "Singleton.h"  
  47. #include <iostream>  
  48. using namespace std;  
  49.  
  50.  
  51. Singleton* Singleton::m_pInstance = 0;  
  52. Singleton::Singleton()  
  53. {  
  54. cout<<"Singleton...."<<endl;  
  55. }  
  56. Singleton* Singleton::Instance()  
  57. {  
  58.     if(NULL == m_pInstance)    
  59.     {  
  60.         locker llock;  
  61.         llock.lock();    
  62.         if(NULL == m_pInstance)    
  63.         {    
  64.             m_pInstance = new Singleton();    
  65.         }    
  66.         llock.unlock();    
  67.     }    
  68.     return m_pInstance;    
  69.  
  70. }  
  71.  
  72. //main.cpp  
  73. #include "Singleton.h"  
  74. #include <iostream>  
  75. using namespace std;  
  76. int main(int argc,char* argv[])  
  77. {  
  78. Singleton* sgn = Singleton::Instance();  
  79. return 0;  
  80. }  

將構造函數聲明爲private,防止被實例化。用一個靜態成員變量和靜態函數實現唯一的對象構造。在靜態函數中new了空間,所以用內嵌的成員對象的析構函數來釋放內存。爲了多線程安全,在建對象之前先加鎖,完成後拆鎖。

多線程需要的頭文件和庫文件見附件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章