#单列模板

#ifndef QTSINGLETON_H
#define QTSINGLETON_H

#include
#include

#define SINGLETON_DECL(Class)
public:
static Class *Instance();
private:
Q_DISABLE_COPY(Class)
static QScopedPointer self;

#define SINGLETON_IMPL(Class)
QScopedPointer Class::self;
Class *Class::Instance() {
if (self.isNull()) {
static QMutex mutex;
QMutexLocker locker(&mutex);
if (self.isNull()) {
self.reset(new Class);
}
}
return self.data();
}

#endif // QTSINGLETON_H

//使用的时候在头文件和实现文件各加一行代码即可
#include “qtsingleton.h”
class Form : public QWidget
{
Q_OBJECT SINGLETON_DECL(Form)
}

SINGLETON_IMPL(Form)
Form::Form(QWidget *parent) : QWidget(parent), ui(new Ui::Form)
{
ui->setupUi(this);
}

你可能感兴趣的:(C++,命令模式)