当前位置:网站首页>简单工厂模式
简单工厂模式
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;
}
边栏推荐
- 基于超参数自动寻优的工控网络入侵检测
- nodeJs--mime module
- 2022/08/01 Study Notes (day21) Generics and Enums
- JSP 如何获取request对象中的路径信息呢?
- C language character and string function summary (2)
- 23.卷积神经网络实战-ResNet
- Knowing the inorder traversal of the array and the preorder traversal of the array, return the postorder history array
- Redis - message publish and subscribe
- Simpson's paradox
- 这 4 款电脑记事本软件,得试试
猜你喜欢
随机推荐
nodeJs--各种路径
BGP综合实验 建立对等体、路由反射器、联邦、路由宣告及聚合
22.卷积神经网络实战-Lenet5
js中内存泄漏的几种情况
【软件工程之美 - 专栏笔记】34 | 账号密码泄露成灾,应该怎样预防?
管理基础知识16
【HCIP】BGP小型实验(联邦,优化)
What is the function of the JSP out.println() method?
管理基础知识13
Constructor, this keyword, method overloading, local variables and member variables
Web开发
期货开户手续费加一分是主流
IO stream basics
How does JSP use request to get the real IP of the current visitor?
21.数据增强
管理基础知识9
Redis 相关问题
What is Low-Code?What scenarios is low code suitable for?
go笔记——map
ICML 2022 || 局部增强图神经网络GNN,在 GCN 和 GAT基础上 平均提高了 3.4% 和 1.6%








