1// SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd.
2//
3// SPDX-License-Identifier: GPL-3.0-or-later
4
5#ifndef QTCLASSFACTORY_H
6#define QTCLASSFACTORY_H
7
8#include "framework/framework_global.h"
9
10#include <QString>
11#include <QObject>
12
13#include <functional>
14
15DPF_BEGIN_NAMESPACE
16
17template<class CT = QObject>
18class QtClassFactory
19{
20 typedef std::function<CT*()> CreateFunc;
21public:
22 virtual ~QtClassFactory() {}
23
24 template<class T>
25 bool regClass(const QString &name, QString *errorString = nullptr)
26 {
27 if (constructList[name]) {
28 if (errorString)
29 *errorString = QObject::tr("The current class name has registered "
30 "the associated construction class");
31 return false;
32 }
33
34 CreateFunc foo = [=](){
35 return dynamic_cast<CT*>(new T());
36 };
37 constructList.insert(name, foo);
38 return true;
39 }
40
41 CT* create(const QString &name, QString *errorString = nullptr)
42 {
43 CreateFunc constantFunc = constructList.value(name);
44 if (constantFunc) {
45 return constantFunc();
46 } else {
47 if (errorString)
48 *errorString = QObject::tr("Should be call registered 'regClass()' function "
49 "before create function");
50 return nullptr;
51 }
52 }
53
54 QStringList createKeys()
55 {
56 return constructList.keys();
57 }
58
59protected:
60 QMap<QString, CreateFunc> constructList;
61};
62
63DPF_END_NAMESPACE
64
65#endif // QTCLASSFACTORY_H
66