This repository has been archived on 2024-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
Doric/doric-Qt/doric/utils/DoricObjectFactory.h

39 lines
924 B
C
Raw Normal View History

2021-02-04 17:04:22 +08:00
#ifndef OBJECTFACTORY_H
#define OBJECTFACTORY_H
2021-02-04 16:59:58 +08:00
#include <QByteArray>
#include <QHash>
#include <QMetaObject>
class DoricObjectFactory {
public:
template <typename T> static void registerClass(QString name) {
constructors().insert(name, &constructorHelper<T>);
}
static bool acquireClass(QString name) {
return constructors().keys().contains(name);
}
static QObject *createObject(const QString &name, QObject *parent = NULL) {
Constructor constructor = constructors().value(name);
if (constructor == NULL)
return NULL;
return (*constructor)(parent);
}
private:
typedef QObject *(*Constructor)(QObject *parent);
template <typename T> static QObject *constructorHelper(QObject *parent) {
return new T(parent);
}
static QHash<QString, Constructor> &constructors() {
static QHash<QString, Constructor> instance;
return instance;
}
};
#endif // OBJECTFACTORY_H