Singleton模式是最常用的設計之一,最近結合自己的實際應用,把Singleton作為模板抽象出來(線程安全),權當拋磚引用,歡迎大家提出批評意見,互相交流。下面為源碼,已經編譯運行過。
Singleton 模板類
- #ifndef _Singleton_h_
- #define _Singleton_h_
-
- #include <pthread.h>
- class Mutex
- {
- public:
- Mutex()
- {
- pthread_mutex_init(&m_lock,NULL);
- }
-
- ~Mutex()
- {
- pthread_mutex_destroy(&m_lock);
- }
-
- void Lock()
- {
- pthread_mutex_lock(&m_lock);
- }
-
- void UnLock()
- {
- pthread_mutex_unlock(&m_lock);
- }
-
- private:
- pthread_mutex_t m_lock;
- };
-
- template<class T>
- class Singleton
- {
- public:
- static T* GetInstance();
- static void Destroy();
- private:
- static T* m_pInstance;
- static Mutex m_mutex;
- };
-
- template<class T>
- T* Singleton<T>::m_pInstance = 0;
-
- template<class T>
- Mutex Singleton<T>::m_mutex;
-
- template<class T>
- T* Singleton<T>::GetInstance()
- {
- if (m_pInstance)
- {
- return m_pInstance;
- }
- m_mutex.Lock();
- if (NULL == m_pInstance)
- {
- m_pInstance = new T;
- }
- m_mutex.UnLock();
- return m_pInstance;
- }
-
- template<class T>
- void Singleton<T>::Destroy()
- {
- if (m_pInstance)
- {
- delete m_pInstance;
- m_pInstance= NULL;
- }
- }
-
- #endif