设计模式——简单工厂模式

本文深入探讨了简单工厂模式的概念,通过代码实例展示了如何使用简单工厂模式创建不同的产品对象,并介绍了其在代码设计中的优点与潜在缺点。此外,文章还提供了小技巧——使用枚举作为函数参数来优化模式应用。

简单工厂模式:


代码:

#include <iostream>
using namespace std;

class Operation
{
public:
virtual int process(int a,int b);
};

int Operation::process(int a,int b)
{
return 0;
}

class AddOperation:public Operation
{
public:
virtual int process(int a,int b);
};


int AddOperation::process(int a,int b)
{
return (a+b);
}

class SubOperation:public Operation
{
public:
virtual int process(int a,int b);
};

int SubOperation::process(int a,int b)
{
return (a-b);
}

class OperationFactory
{
public:
   Operation* CreateOperation(int c);
};

Operation* OperationFactory::CreateOperation(int c)
{
Operation* myOperation = NULL;
switch (c)
{
case 1:
        myOperation = new AddOperation;
break;
case 2:
        myOperation = new SubOperation;
break;
default:
break;
}
return myOperation;
}

void main()
{
OperationFactory* c_Operation = new OperationFactory; //new必须用指针接收
Operation* oper = c_Operation->CreateOperation(1);
int result = oper->process(1,1);
cout<<result<<endl;
return;
}


小技巧:枚举作为函数参数


SingleCore* CreateSingleCore(enum CTYPE ctype) 


优点 :

1、工厂类中包含了必要的判断逻辑,根据客户端的选择条件动态实例化相关的类。对于客户端来说,去除了与相关产品的依赖。


缺点:

1、需要在工厂类中做判断,从而创造相应的产品。当增加新的产品时,就需要修改工厂类。对于扩展开放,对修改也开放了。违背了“开放封闭原则”。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值