当前位置:网站首页>简单工厂模式
简单工厂模式
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;
}
边栏推荐
- ICML 2022 | GraphFM:通过特征Momentum提升大规模GNN的训练
- 构造方法,this关键字,方法的重载,局部变量与成员变量
- 测试用例:四步测试设计法
- Active Disturbance Rejection Control of Substation Inspection Robot Based on Data Drive
- [21-Day Learning Challenge] A small summary of sequential search and binary search
- Looking back at 5 recessionary times in history: How might this time be different?
- 管理基础知识12
- c语言字符和字符串函数总结(二)
- 期货开户手续费的秘密成了透明
- An Enhanced Model for Attack Detection of Industrial Cyber-Physical Systems
猜你喜欢
随机推荐
Kotlin协程:创建、启动、挂起、恢复
An Enhanced Model for Attack Detection of Industrial Cyber-Physical Systems
Multi-feature fusion face detection based on attention mechanism
路由策略
【HCIP】BGP小型实验(联邦,优化)
如何期货开户和选择期货公司?
Don't know about SynchronousQueue?So ArrayBlockingQueue and LinkedBlockingQueue don't and don't know?
NodeJs, all kinds of path
21.数据增强
JSP page指令errorPage属性起什么作用呢?
Industrial control network intrusion detection based on automatic optimization of hyperparameters
Pytorch seq2seq 模型架构实现英译法任务
Unknown CMake command “add_action_files“
bgp aggregation reflector federation experiment
思维导图,UML在线画图工具
js中内存泄漏的几种情况
基于相关性变量筛选偏最小二乘回归的多维相关时间序列建模方法
Statement执行update语句
C语言:打印整数二进制的奇数位和偶数位
期货开户手续费的秘密成了透明