| 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 | |
| 15 | DPF_BEGIN_NAMESPACE |
| 16 | |
| 17 | template<class CT = QObject> |
| 18 | class QtClassFactory |
| 19 | { |
| 20 | typedef std::function<CT*()> CreateFunc; |
| 21 | public: |
| 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 | |
| 59 | protected: |
| 60 | QMap<QString, CreateFunc> constructList; |
| 61 | }; |
| 62 | |
| 63 | DPF_END_NAMESPACE |
| 64 | |
| 65 | #endif // QTCLASSFACTORY_H |
| 66 |