Qt中实现工厂模式
在Qt中实现工厂模式可以通过多种方式,具体选择取决于需求和场景。以下是几种常见的实现方法:
在Qt中实现工厂模式可以通过多种方式,具体选择取决于需求和场景。以下是几种常见的实现方法:
cppclass Shape {public: virtual void draw() = 0; virtual ~Shape() = default;};class Circle : public Shape {public: void draw() override { qDebug() << "Drawing Circle"; }};class Rectangle : public Shape {public: void draw() override { qDebug() << "Drawing Rectangle"; }};class ShapeFactory {public: static Shape* createShape(const QString& type) { if (type == "Circle") return new Circle(); if (type == "Rectangle") return new Rectangle(); return nullptr; }};// 使用Shape* circle = ShapeFactory::createShape("Circle");circle->draw(); // 输出: Drawing Circle
### 2. **动态注册工厂(扩展性好)**使用注册表动态注册创建函数,支持扩展。cppclass ShapeFactory {public: using Creator = std::function<Shape*()>; static void registerCreator(const QString& type, Creator creator) { creators()[type] = creator; } static Shape* create(const QString& type) { auto it = creators().find(type); return (it != creators().end()) ? it->second() : nullptr; }private: static QMap<QString, Creator>& creators() { static QMap<QString, Creator> instance; return instance; }};// 注册具体类struct CircleRegistrar { CircleRegistrar() { ShapeFactory::registerCreator("Circle", []{ return new Circle; }); }} static circleRegistrar;// 使用Shape* shape = ShapeFactory::create("Circle");
### 3. **利用Qt元对象系统(QObject派生类)**通过类名动态创建对象,需配合Qt的元对象系统。cppclass Shape : public QObject { Q_OBJECTpublic: virtual void draw() = 0;};class Circle : public Shape { Q_OBJECTpublic: void draw() override { qDebug() << "Circle"; }};// 注册元类型Q_DECLARE_METATYPE(Circle*)qRegisterMetaType<Circle*>();// 使用类名创建实例const QMetaObject* meta = QMetaType::metaObjectForType(QMetaType::type("Circle"));Shape* obj = qobject_cast<Shape*>(meta->newInstance());
### 4. Qt插件系统结合工厂模式动态加载插件并创建实例,适合扩展应用。接口定义 (shapeplugin.h):cpp#include <QtPlugin>class Shape {public: virtual void draw() = 0; virtual ~Shape() = default;};#define ShapeInterface_iid "com.example.ShapeInterface"Q_DECLARE_INTERFACE(Shape, ShapeInterface_iid)
插件实现 (circleplugin.cpp):cppclass CirclePlugin : public QObject, public Shape { Q_OBJECT Q_PLUGIN_METADATA(IID ShapeInterface_iid FILE "circle.json") Q_INTERFACES(Shape)public: void draw() override { qDebug() << "Circle Plugin"; }};#include "circleplugin.moc"
加载插件:cppQPluginLoader loader("circleplugin.dll");QObject* plugin = loader.instance();if (plugin) { Shape* shape = qobject_cast<Shape*>(plugin); shape->draw(); // 输出: Circle Plugin}
### 总结- 简单工厂:适用于类型较少且不常变化的场景。- 动态注册:扩展性好,新增类型无需修改工厂。- 元对象系统:适合QObject派生类,利用Qt的反射机制。- 插件系统:实现动态扩展,适用于模块化设计。根据具体需求选择合适的方式,确保代码的灵活性和可维护性。