在程序開發中,某一個類對象常常須要在好多個類中使用,爲測試方便,好多初學者聲明一個該類的全局變量,而後在其它類中引用使用。設計模式
可是,好的編碼是能不用全局變量就不用全局變量。函數
這些類對象每每時單一的對象,因而可使用設計模式中的單例模式來很好地規避全局變量的使用。測試
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
#ifndef
SINGLETON_H #define SINGLETON_H #include <QMutex> template < typename T, typename L = QMutex> class Singleton { public : template < typename ...Args> static T *getSingleton(Args&&... args) { if (!m_init) { if (nullptr == m_inst) { m_lock.lock(); m_init = new T(std::forward<Args>(args)...); m_init = true ; m_lock.unlock(); } } return m_inst; } private : Singleton() {} private : static bool m_init; static T *m_inst; static L m_lock; }; template < typename T, typename L> bool Singleton<T, L>::m_init = false ; template < typename T, typename L> T *Singleton<T, L>::m_inst = nullptr; template < typename T, typename L> L Singleton<T, L>::m_lock; #endif // SINGLETON_H |
使用:編碼
您的類名 *對象指針名 = Singleton<您的類名>::getSingleton([構造函數參數列表,可選]);spa
1
2 3 4 5 6 7 8 9 10 11 |
class
WindowService { public : WindowService( const QString &name) { m_name = name; } ~WindowService() {} private : QString m_name; }; WindowService *winSvr = Singleton<WindowService>::getSingleton( "WindowService" ); |
祝您使用愉快!.net