目录
前言
工厂方法模式是常用的对象创建型设计模式,核心是封装类中不变的部分作为抽象基类的方法,提取个性化易变部分作为独立类,通过继承注入以达到解耦、复用的目的。
一、模式关键点
抽象工厂:是工厂方法的核心,任何在该模式中创建的对象的工厂类必须实现这个接口。
具体工厂:实现抽象工厂接口的具体工厂类,被调用以创建具体的产品对象。
抽象产品:具体产品的共同父类或共同拥有的接口。
具体产品:实现抽象产品角色所定义的接口,某具体产品由具体工厂创建
二、应用场景
一个类不知道它所需要的对象类,在工厂方法模式中,客户端不需要指定具体产品类的类名,只需要知道所对应的工厂即可,具体的产品对象由具体的工厂类创建,客户端只需要知道创建具体产品的工厂即可
三、具体案例
比较经典的工厂生产水果案例,水果包括苹果、香蕉、桃子
水果产品类文件
#ifndef PRODUCT_H
#define PRODUCT_H
//水果产品基类
class AFruits
{
public:
virtual QString name()=0;
};
//具体水果产品
class Apple : public AFruits
{
public:
virtual QString name()
{
return "This is Apple";
}
};
class Banana : public AFruits
{
public:
virtual QString name()
{
return "this is Banana";
}
};
class Peach : public AFruits
{
public:
virtual QString name()
{
return "this is Peach";
}
};
#endif // PRODUCT_H
工厂类文件
#ifndef FACTORY_H
#define FACTORY_H
#include "product.h"
//抽象工厂基类
class AFactory
{
public:
virtual AFruits * CreateProduct()=0;
};
//具体工厂类
class AppleFactory : public AFactory
{
public:
virtual AFruits *CreateProduct()
{
return new Apple();
}
};
class BananaFactory : public AFactory
{
public:
virtual AFruits *CreateProduct()
{
return new Banana();
}
};
class PeachFactory : public AFactory
{
public:
virtual AFruits *CreateProduct()
{
return new Peach();
}
};
#endif // FACTORY_H
客户端使用
#include <QCoreApplication>
#include <QDebug>
#include "factory.h"
#ifndef POINT_DELETE
#define POINT_DELETE(p) {if(p){delete(p);(p)=nullptr;}}
#endif
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//苹果
AFactory * pFactory = new AppleFactory();
AFruits *pFruits = pFactory->CreateProduct();
qDebug() << pFruits->name()<<endl;
POINT_DELETE(pFactory);
POINT_DELETE(pFruits);
//香蕉
pFactory = new BananaFactory();
pFruits=pFactory->CreateProduct();
qDebug() << pFruits->name()<<endl;
POINT_DELETE(pFactory);
POINT_DELETE(pFruits);
//桃子
pFactory=new PeachFactory();
pFruits=pFactory->CreateProduct();
qDebug() << pFruits->name();
POINT_DELETE(pFactory);
POINT_DELETE(pFruits);
return a.exec();
}
输出结果如下图
总结
工厂方法模式使用简单且应用普遍,本实例在Qt Creator中创建,应用QT的控制台程序,编译器使用的mingw