当前位置:网站首页>工厂方法模式
工厂方法模式
2022-08-02 12:33:00 【l_ethan】
简介:工厂方法模式的意义是定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类当中。核心工厂类不在负责产品的创建,这样核心类成为一个抽象工厂角色,仅负责具体工厂子类必须实现的接口,这样进一步抽象化的好处是使得工厂方法模式可以使系统在不修改具体工厂角色的情况下引进新的产品。
工厂方法模式是简单工厂模式的衍生,解决了许多简单工厂模式的问题。首先完全实现’开-闭‘原则,实现了可拓展。
优点:
1.不需要记住具体类名
2.实现了对象创建和使用的分离
3.系统的可扩展性也就变地非常好无需修改接口和原类。
缺点:
1.增加系统中类的个数,复杂度和理解度增加
2.增加了系统的抽象性和理解难度
案例:
#include <iostream>
using namespace std;
class AbstractFruit {
public:
virtual void show() = 0;
};
class Apple :public AbstractFruit {
public:
virtual void show() {
cout << "apple" << endl;
}
};
class Banana :public AbstractFruit {
public:
virtual void show() {
cout << "banana" << endl;
}
};
class AbstractFruitFactor {
public:
virtual AbstractFruit* createfruit()=0;
};
class AppleFactor :public AbstractFruitFactor {
public:
virtual AbstractFruit* createfruit() {
return new Apple;
}
};
class BananaFactor :public AbstractFruitFactor {
public:
virtual AbstractFruit* createfruit() {
return new Banana;
}
};
int main()
{
AbstractFruitFactor* af = nullptr;
AbstractFruit* f = nullptr;
af = new AppleFactor;
f = af->createfruit();
f->show();
delete af;
delete f;
return 0;
}
边栏推荐
猜你喜欢
随机推荐
30 lines of code to realize serverless real-time health code recognition -- operation manual
SQL Server修改数据
The ex-boyfriend bought chili water and threatened to rob his daughter. Can the woman apply for a personal safety protection order?
ABAP-OOAVL template program
The use of QListView
如何关闭开启硬件加速[通俗易懂]
Openlayers 快速上手教程
FreeRTOS--栈实验
Basic operations of openGauss database (super detailed)
Intelligent Image Analysis-Intelligent Home Appliance Image Target Detection Statistical Counting Detection and Recognition-iCREDIT
用位运算为你的程序加速
Thymeleaf
1.3快速生成树协议RSTP
How to better assess credit risk?Just watch this scorecard model live
js炫酷仪表盘插件
Manual architecture, Mysql interview 126 questions
js九宫格样式抽奖插件
numpy&pands 中的unique
看我如何用多线程,帮助运营小姐姐解决数据校对系统变慢!
SQL Server 2014 installation tutorial (nanny-level graphic tutorial)