factoty qt

__040711563a17902392e7

海前 王

Posted on September 2, 2024

factoty qt
#include <QCoreApplication>
#include <QObject>
#include <QDebug>
#include <QMap>
#include <QString>

// 基类
class MyBase : public QObject {
    Q_OBJECT
public:
    explicit MyBase(QObject *parent = nullptr) : QObject(parent) {}
    virtual void doSomething() = 0;
};

// 派生类1
class MyDerived1 : public MyBase {
    Q_OBJECT
public:
    explicit MyDerived1(QObject *parent = nullptr) : MyBase(parent) {}
    void doSomething() override {
        qDebug() << "MyDerived1 doing something!";
    }
};

// 派生类2
class MyDerived2 : public MyBase {
    Q_OBJECT
public:
    explicit MyDerived2(QObject *parent = nullptr) : MyBase(parent) {}
    void doSomething() override {
        qDebug() << "MyDerived2 doing something!";
    }
};

// 工厂类
class MyFactory {
public:
    // 注册工厂函数
    static void registerClass(const QString& className, QObject* (*creator)()) {
        getRegistry()[className] = creator;
    }

    // 创建对象
    static MyBase* createObject(const QString& className) {
        auto it = getRegistry().find(className);
        if (it != getRegistry().end()) {
            QObject* (*creator)() = it.value();
            qDebug() << "Creating object for class:" << className;
            return qobject_cast<MyBase*>(creator());
        }
        qDebug() << "Class not found:" << className;
        return nullptr;
    }

private:
    // 获取注册表
    static QMap<QString, QObject* (*)()>& getRegistry() {
        static QMap<QString, QObject* (*)()> registry;
        return registry;
    }
};

// 定义工厂函数
QObject* createMyDerived1() { return new MyDerived1(); }
QObject* createMyDerived2() { return new MyDerived2(); }

// 注册类
static bool registered1 = []() {
    MyFactory::registerClass("MyDerived1", createMyDerived1);
    return true;
}();

static bool registered2 = []() {
    MyFactory::registerClass("MyDerived2", createMyDerived2);
    return true;
}();

// 主函数
int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);

    // 使用工厂创建对象
    QString className1 = "MyDerived1";
    QString className2 = "MyDerived2";

    MyBase* obj1 = MyFactory::createObject(className1);
    MyBase* obj2 = MyFactory::createObject(className2);

    // 使用对象
    if (obj1) {
        obj1->doSomething();
        delete obj1;
    }

    if (obj2) {
        obj2->doSomething();
        delete obj2;
    }

    return app.exec();
}

#include "main.moc"

Enter fullscreen mode Exit fullscreen mode

`

💖 💪 🙅 🚩
__040711563a17902392e7
海前 王

Posted on September 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related