歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Singleton模式Linux下的C++實現

Singleton模式Linux下的C++實現

日期:2017/3/1 10:26:21   编辑:Linux編程

Singleton模式是最常用的設計之一,最近結合自己的實際應用,把Singleton作為模板抽象出來(線程安全),權當拋磚引用,歡迎大家提出批評意見,互相交流。下面為源碼,已經編譯運行過。

Singleton 模板類

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