Created
October 16, 2014 14:47
-
-
Save wengxt/92303754d4a45c71edae to your computer and use it in GitHub Desktop.
simple-qobject-factory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QObject> | |
#include <QDebug> | |
class FactoryBase | |
{ | |
public: | |
virtual QObject* create() = 0; | |
}; | |
QMap<QString, FactoryBase*> factoryMap; | |
template<class T> | |
class Factory : public FactoryBase | |
{ | |
public: | |
Factory() { | |
factoryMap.insert(T::staticMetaObject.className(), this); | |
} | |
virtual QObject* create() { | |
return new T; | |
} | |
}; | |
class CA : public QObject | |
{ | |
Q_OBJECT | |
public: | |
explicit CA(QObject* parent = 0) : QObject(parent) {} | |
Q_INVOKABLE void printSomething() { qDebug() << "This is CA"; } | |
}; | |
Factory<CA> caFactory; | |
class CB : public QObject | |
{ | |
Q_OBJECT | |
public: | |
explicit CB(QObject* parent = 0) : QObject(parent) {} | |
Q_INVOKABLE void printSomething() { qDebug() << "This is CB"; } | |
}; | |
Factory<CB> CBFactory; | |
int main(int argc, char* argv[]) { | |
Q_UNUSED(argc); | |
Q_UNUSED(argv); | |
QObject* obj1 = factoryMap["CA"]->create(); | |
QMetaObject::invokeMethod(obj1, "printSomething"); | |
QObject* obj2 = factoryMap["CB"]->create(); | |
QMetaObject::invokeMethod(obj2, "printSomething"); | |
delete obj1; | |
delete obj2; | |
return 0; | |
} | |
#include "main.moc" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment