接着前面所述简单工厂模式,简单工厂模式符合面向对象4大原则:可维护,可复用,可扩展,灵活性高,耦合度低,但是他仍然有一个很
大的问题就是如果要增加新的产品,必须对工厂进行修改,这就违背了软件设计的开闭原则 。
对于这种问题,我们可以使用工厂模式来解决。
假设我们想要增加一个新的运算乘方运算类,我们可以按如下思想来设计:
设计基于运算基类的乘方类,这和简单工厂模式相同,但在设计工厂的时候,我们把他的加工产品的方式分类,并且设计一个总厂(工厂基
类),这样,我们需要产品的时候,只需要向总厂请求,总厂让分厂来生产产品,如果有新的产品需要加工,只需设计一个新的工厂来加工
新产品就可以了,不需要对原厂进行更改。
实现代码:
这里继续引用简单工厂模式中的计算器类,对于原有的产品(运算类和运算基类)我们不做更改,我们只设计新的工厂;
//乘方类
#ifndef OPERATIONPOWER
#define OPERATIONPOWER
class OperationPower:public Operation
{
public:double GetResult(double numA, double numB);
};
#endif
//基类工厂
#ifndef FACTORY
#define FACTORY
class Factory
{
public:virtual Operation * CreateOperation(char operate);
};
#endif
//原有的基础运算基类
#ifndef FACTORY1
#define FACTORY1
class Factory1:public Factory
{
public:Operation *CreateOperation(char operate);
};
#endif
//运算基类实现
Operation *Factory1::CreateOperation(char operate)
{
std::cout<<"It is the Factory1!"<<std::endl;
Operation *oper = NULL;
switch(operate)
{
case '+':oper = new OperationAdd();
break;
case '-':oper = new OperationSub();
break;
case '*':oper = new OperationMul();
break;
case '/':oper = new OperationDiv();
break;
default: std::cout<<"The Operation is Error!"<<std::endl;
oper = new Operation();
break;
}
return oper;
}
//新增加乘方运算处理工厂
#ifndef FACTORYNEW1
#define FACTORYNEW1
class FactoryNew1:public Factory
{
public:Operation *CreateOperation(char operate);
};
#endif
//处理工厂实现
Operation *FactoryNew1::CreateOperation(char operate)
{
std::cout<<"It is a New Factory!/n";
Operation *oper = NULL;
switch(operate)
{
case '^':oper = new OperationPower();
break;
case 'e':exit(0);
break;
default:
std::cout<<"The Operation is Error!"<<std::endl;
oper = new Operation();
break;
}
return oper;
}
//客户端实现
int main(void)
{
Factory *p = new Factory1();
Operation *oper = p->CreateOperation('+');
double result = 0;
double numA = 20;
double numB = 4;
result = oper->GetResult(numA, numB);
std::cout<<"numA + numB 's result is:"<<result<<"/n";
delete p;
delete oper;
p = new FactoryNew1();
oper = p->CreateOperation('^');
result = oper->GetResult(numA, numB);
std::cout<<"numA ^ numB 's result is:"<<result<<"/n";
system("pause");
return 0;
}
说明:
/*
*优点:弥补了简单工程模式的不足,扩充新的产品不在需要改动工厂,可直接设计子工厂就可完成
*缺点:对创造不同系列的新产品无能为力
*/