product.h
#ifndef PRODUCT_H #define PRODUCT_H #include <QtDebug> class Product { public: Product(){} virtual void show() = 0; }; #endif // PRODUCT_HproductA.h
#ifndef PRODUCTA_H #define PRODUCTA_H #include "product.h" class ProductA : public Product { public: ProductA(){} void show(){ qDebug() << "this is ProductA";} }; #endif // PRODUCTA_Hfactory.h
#ifndef FACTORY_H #define FACTORY_H #include "product.h" class Factory { public: Factory(){} virtual Product *createProduct() = 0; }; #endif // FACTORY_HfactoryA.h
#ifndef FACTORYA_H #define FACTORYA_H #include "factory.h" #include "productA.h" #include "product.h" class FactoryA : public Factory { public: FactoryA(){} Product *createProduct() { return new ProductA(); } }; #endif // FACTORYA_Hmain
#include <QApplication> #include <QtDebug> #include "factory.h" #include "factoryA.h" #include "product.h" //工厂方法模式 int main(int argc, char *argv[]) { QApplication a(argc, argv); Factory *factory = new FactoryA(); Product *product = factory->createProduct(); product->show(); return a.exec(); }相对于简单工厂,工厂方法对工厂对象进行了封装,一个工厂只创建一种产品。新增产品,新增工厂,不同于简单工厂需要修改工厂中的判断条件。这符合开放-封闭原则
UML