简单工厂模式和工厂模式的区别:
简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态的实例化相关的类,对于客户端来说,除去了与具体产品的依赖。就像计算器,让客户端不用管该用哪个类的实例,只需把'+'给工厂,工厂自动就给出了相应的实例,客户端只要做运算就可以了。但是问题也在这里,如果要增加新的运算功能,就一定需要修改这个运算工厂类,违背了开放-封闭原则。
工厂方法模式,定义一个用于创造对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,也就是说,工厂模式把简单工厂的内部逻辑判断转移到了客户端代码来进行,增加功能时,需要修改客户端。
#include <iostream>
#include <stdexcept>
#include <memory>
using namespace std;
class Operation
{
protected:
double numberA;
double numberB;
public:
void GetNumberA(double value)
{
numberA = value;
}
void GetNumberB(double value)
{
numberB = value;
}
virtual double GetResult() = 0;
};
class OperationAdd : public Operation
{
public:
virtual double GetResult()
{
double result = numberA + numberB;
return result;
}
};
class OperationSub : public Operation
{
public:
virtual double GetResult()
{
double result = numberA - numberB;
return result;
}
};
class OperationMul : public Operation
{
public:
virtual double GetResult()
{
double result = numberA * numberB;
return result;
}
};
class OperationDiv : public Operation
{
public:
virtual double GetResult()
{
if( (-0.0000001< numberB) && (numberB < 0.0000001) )
throw exception("除数不能为0");
double result = numberA / numberB;
return result;
}
};
/*运算符工厂类*/
class OperationFactory
{
public:
virtual Operation* CreateOperation() = 0; //子类实现这个方法,返回具体的运算法对象
};
/*加法运算符工厂类,继承OperationFactory抽象类,实现CreateOperation方法,返回加法运算符对象*/
class AddOperationFactory : public OperationFactory
{
public:
virtual Operation* CreateOperation()
{
return new OperationAdd();
}
};
class SubOperationFactory : public OperationFactory
{
public:
virtual Operation* CreateOperation()
{
return new OperationSub();
}
};
class MulOperationFactory : public OperationFactory
{
public:
virtual Operation* CreateOperation()
{
return new OperationMul();
}
};
class DivOperationFactory : public OperationFactory
{
public:
virtual Operation* CreateOperation()
{
return new OperationDiv();
}
};
int main()
{
double numberA;
double numberB;
char operate;
cout<<"请输入数字A: ";
cin>>numberA;
cout<<"请输入数字B: ";
cin>>numberB;
AddOperationFactory addfa;
SubOperationFactory subfa;
MulOperationFactory mulfa;
DivOperationFactory divfa;
OperationFactory* factory = &divfa; /* 只需替换具体的操作符对象即可 */
Operation* oper = factory->CreateOperation();
oper->GetNumberA(numberA);
oper->GetNumberB(numberB);
try{
cout<<oper->GetResult()<<endl;
}
catch(exception& e)
{
cout<<e.what()<<endl;
}
delete oper;
return 0;
}