Skip to content

Instantly share code, notes, and snippets.

@SunRain
Forked from wengxt/simple-qobject-factory.c
Last active August 29, 2015 14:07
Show Gist options
  • Save SunRain/2220aa0a59d481a7ed15 to your computer and use it in GitHub Desktop.
Save SunRain/2220aa0a59d481a7ed15 to your computer and use it in GitHub Desktop.
#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