简单工厂模式:

代码:
#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、需要在工厂类中做判断,从而创造相应的产品。当增加新的产品时,就需要修改工厂类。对于扩展开放,对修改也开放了。违背了“开放封闭原则”。
本文深入探讨了简单工厂模式的概念,通过代码实例展示了如何使用简单工厂模式创建不同的产品对象,并介绍了其在代码设计中的优点与潜在缺点。此外,文章还提供了小技巧——使用枚举作为函数参数来优化模式应用。
1037

被折叠的 条评论
为什么被折叠?



