当前位置:网站首页>简单工厂模式
简单工厂模式
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;
}
边栏推荐
猜你喜欢
随机推荐
路由策略
JS中对事件代理的理解及其应用场景
管理基础知识13
不要用jOOQ串联字符串
【CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes!)(A~D)】
nodeJs--mime module
Don't know about SynchronousQueue?So ArrayBlockingQueue and LinkedBlockingQueue don't and don't know?
期货开户调整交易所保证金标准
460. LFU cache
Redis的集群模式
思维导图,UML在线画图工具
Simpson's paradox
什么是低代码(Low-Code)?低代码适用于哪些场景?
How to find new potential projects?Tools recommended
JS中对作用域链的理解(查找变量)
els block boundary deformation processing
MySQL常用语句整理
Kotlin协程:创建、启动、挂起、恢复
els block deformation judgment.
ROS dynamic parameters