工厂模式
定义
- 工厂父类负责定义创建对象的公共接口,子类则负责生成具体的对象
- 将类的实例化(具体产品的创建)延迟到工厂类的子类(具体工厂)中完成,即由子类来决定应该实例化哪个类
类图
- 组成
- 抽象产品
- 具体产品
- 抽象工厂
- 具体工厂
时序图
应用场景
- 设计初期就考虑到产品在后期会进行扩展的情况下,可以使用工厂模式
- 产品结构复杂的情况下,可以使用工厂方法模式
代码
/**
* 工厂模式: 工厂父类负责定义创建对象的公共接口,而子类负责生成具体的对象
*
*/
#include<iostream>
using namespace std;
class AbstractFruit{
public:
virtual void showName() = 0;
};
class Apple : public AbstractFruit {
public:
virtual void showName() {
cout << "This is the class of Apple" << endl;
}
};
class Banana : public AbstractFruit {
public:
virtual void showName() {
cout << "This is the class of Banana" << endl;
}
};
class Pear : public AbstractFruit {
public:
virtual void showName() {
cout << "This is the class of Pear" << endl;
}
};
class AbstractFactory{
public:
virtual AbstractFruit* createFruit() = 0;
};
class AppleFactory : public AbstractFactory {
public:
virtual AbstractFruit* createFruit(){
return new Apple;
}
};
class BananaFactory : public AbstractFactory {
public:
virtual AbstractFruit* createFruit(){
return new Banana;
}
};
class PearFactory : public AbstractFactory {
public:
virtual AbstractFruit* createFruit(){
return new Pear;
}
};
int main()
{
AbstractFactory* CPFactory = nullptr;
AbstractFruit* CPFruit = nullptr;
CPFactory = new AppleFactory();
CPFruit = CPFactory->createFruit();
CPFruit->showName();
CPFactory = new BananaFactory();
CPFruit = CPFactory->createFruit();
CPFruit->showName();
CPFactory = new PearFactory();
CPFruit = CPFactory->createFruit();
CPFruit->showName();
return 0;
}