当前位置:网站首页>简单工厂模式
简单工厂模式
2022-08-02 00:16:00 【l_ethan】
定义:定义了一个创建对象的类,由这个类来封装实例化对象的行为。
优点:
1.客户端和具体实现类解耦
2.对于某些对象创建过程比较复杂,我们不考虑
缺点:
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 FruitFactor {
public:
static AbstractFruit* createFruit(string flag) {
if (flag == "apple")
return new Apple;
else if (flag == "banana")
return new Banana;
else {
return NULL;
}
}
};
int main()
{
FruitFactor* factory = new FruitFactor;
AbstractFruit* fruit = factory->createFruit("apple");
fruit->show();
return 0;
}
边栏推荐
- Grid false data injection attacks detection based on coding strategy
- 基于编码策略的电网假数据注入攻击检测
- Day11 shell脚本基础知识
- Realize deletion - a specified letter in a string, such as: the string "abcd", delete the "a" letter in it, the remaining "bcd", you can also pass multiple characters to be deleted, and pass "ab" can
- JS中对作用域链的理解(查找变量)
- 技术分享 | 接口测试中如何使用Json 来进行数据交互 ?
- 构造方法,this关键字,方法的重载,局部变量与成员变量
- uni-app项目总结
- uni-app project summary
- Kotlin协程:创建、启动、挂起、恢复
猜你喜欢
随机推荐
Detailed explanation of JSP request object function
管理基础知识9
具有通信时延的多自主体系统时变参考输入的平均一致性跟踪
How to use the go language standard library fmt package
Don't know about SynchronousQueue?So ArrayBlockingQueue and LinkedBlockingQueue don't and don't know?
C language character and string function summary (2)
技术分享 | 接口测试中如何使用Json 来进行数据交互 ?
Industrial control network intrusion detection based on automatic optimization of hyperparameters
Are test points the same as test cases?
MySQL常用语句整理
MLX90640 红外热成像仪测温模块开发笔记(完整版)
Cyber-Physical System State Estimation and Sensor Attack Detection
管理基础知识19
Web开发
ICML 2022 || 局部增强图神经网络GNN,在 GCN 和 GAT基础上 平均提高了 3.4% 和 1.6%
Redis 相关问题
业务测试如何避免漏测 ?
bgp 聚合 反射器 联邦实验
期货开户手续费加一分是主流
JS中的防抖和节流