在程序开发中,某一个类对象常常须要在好多个类中使用,为测试方便,好多初学者声明一个该类的全局变量,而后在其它类中引用使用。设计模式
可是,好的编码是能不用全局变量就不用全局变量。函数
这些类对象每每时单一的对象,因而可使用设计模式中的单例模式来很好地规避全局变量的使用。测试
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