C++实现单例模式

来源:互联网 发布:apowersoft录屏王 mac 编辑:程序博客网 时间:2024/05/24 22:46

转自:http://buptdtt.blog.51cto.com/2369962/975101


  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了空间,所以用内嵌的成员对象的析构函数来释放内存。为了多线程安全,在建对象之前先加锁,完成后拆锁。

多线程需要的头文件和库文件见附件


原创粉丝点击