#include <iostream>
class Calculator
{
public:
virtual double cal()=0;
Calculator(){}
void setValue(double _a, double _b)
{
a=_a;
b=_b;
}
public:
double a;
double b;
};
class Factory
{
virtual Calculator * create()=0;
};
class CalculatorAdd : public Calculator
{
public:
double cal()
{
return a+b;
}
};
class FactoryAdd: public Factory
{
public:
CalculatorAdd * create()
{
return new CalculatorAdd();
}
};
class CalculatorMinus : public Calculator
{
public:
double cal()
{
return a - b;
}
};
class FactoryMinus : public Factory
{
public:
CalculatorMinus * create()
{
return new CalculatorMinus();
}
};
//这样做的好处是: 隐藏了CalculatorAdd类, 如果后续我们需要修改Add方法, 只需要修改CalculatorAdd方法, 或者增加一个你需要的
//CalculaterAddPlus类就行了, 而不必要修改源码源代码不需要修改,
int main()
{
FactoryAdd fac ;
Calculator* cal = fac.create();
cal->setValue(1,2);
std::cout<< cal->cal();
}
注:
工厂模式和策略模式的区别: 工厂模式强调代码隐藏,解耦合, 策略模式强调方法的可替换性。