Qt代码举例-单例模式
使用Qt方便的实现单例模式
单例类的实现,其中qCallOnce函数是确保该函数只执行一次:
#ifndef SINGLETON #define SINGLETON #include <QtGlobal> #include <QScopedPointer> #include "call_once.h" template <class T> class Singleton { public: static T& instance() { qCallOnce(init, flag); return *tptr; } static void init() { tptr.reset(new T); } private: Singleton() {} ~Singleton() {} Q_DISABLE_COPY(Singleton) static QScopedPointer<T> tptr; static QBasicAtomicInt flag; }; template<class T> QScopedPointer<T> Singleton<T>::tptr(0); template<class T> QBasicAtomicInt Singleton<T>::flag = Q_BASIC_ATOMIC_INITIALIZER(CallOnce::CO_Request); #endif // SINGLETON
使用举例:
1 class TestClass : public QObject 2 { 3 }; 4 #define TestClassInstance Singleton<TestClass >::instance()
还有一种更简单的:
#include <QMutexLocker> class TestClass { public: inline static TestClass* nstance() { QMutexLocker locker(&mutex); if (NULL == m_instance) { m_instance = new TestClass(); } return m_instance; } private: static QMutex mutex; static TestClass* m_instance; };