-
The Singleton pattern restricts a class so that only one instance can be created. This can be accomplished by making its constructor private or protected and providing an instance() function that creates a new instance if one does not already exist, but returns a pointer or reference to that instance if it does.
Singleton(单件) 模式的意图是:保证类仅有一个实例,并提供一个访问它的全局访问点。
应用于多线程环境的 Singleton 模式又叫做 Double-Checked Locking(双重检查锁定)模式。
代码
- singleton.h
#include <QObject> #include <QMutex> #include <QMutexLocker> class Singleton:public QObject { public: static Singleton* instance() { static QMutex mutex; if (!m_instance) { QMutexLocker locker(&mutex); if (!m_instance) m_instance = new Singleton; } return m_instance; } private: Singleton(); static Singleton* m_instance; };
- singleton.cpp
#include <QtCore/QCoreApplication> #include "singleton.h" Singleton *Singleton::m_instance = 0; Singleton::Singleton(): QObject(qApp) { }
在C++中实现单件模式时,何时销毁对象似乎总是一个问题。在Qt中,由于程序中(一般)会有一个QCoreApplication或其派生类的对象,再加上QObject半自动的内存管理方式。我们将QCoreApplication的对象作为该单件对象的父对象,问题就应该迎刃而解了。
QCoreApplication
按照前面的说法:保证类仅有一个实例,并提供一个访问它的全局访问点 。QCoreApplication也应该属于单件模式。不过它的实现有点变态(中性词哈),看看它的代码:
- qcoreapplication.h
class Q_CORE_EXPORT QCoreApplication : public QObject { public: QCoreApplication(int &argc, char **argv); static QCoreApplication *instance() { return self; } ... private: void init(); static QCoreApplication *self; ... };
- qcoreapplication.cpp
QCoreApplication *QCoreApplication::self = 0; QCoreApplication::QCoreApplication(int &argc, char **argv) { init(); ... } void QCoreApplication::init() { Q_ASSERT_X(!self, "QCoreApplication", "there should be only one application object"); QCoreApplication::self = this; ... }
qApp
有人可能对这个宏感兴趣
- qcoreapplication.h
#define qApp QCoreApplication::instance()
- qapplication.h
#if defined(qApp) #undef qApp #endif #define qApp (static_cast<QApplication *>(QCoreApplication::instance()))
如果我们要派生QCoreApplication或QApplication,可能也会考虑重定义该宏。
参考
- Design Patterns Explained, Chapter 16
- Introduction to Design Patterns in C++ with Qt 4, chapter 16
-
http://www.qtcentre.org/wiki/index.php?title=Singleton_pattern