1.逻辑和界面分离
------将数据输入和输出与实际的计算类进行分离
2.面向对象的封装,继承和多态
------实现计算类时,使用面向对象的思想
优点:不用关注内部实现,只需要传入操作码。工厂类中包含了必要的判断逻辑,工具客户端的选择动态实例化相关的类。对于界面来说去除了对具体产品的依赖。
缺点:若新增操作,则需要新增操作类并且修改工厂方法,若工厂方法出现失误则所有的操作类无法正常运行。
实现代码如下:
#include <stdio.h>
using namespace std;
class OperateTmp
{
public:
double numA;
double numB;
virtual double GetResult() = 0;
};
class Add: public OperateTmp
{
public:
double GetResult()
{
return numA + numB;
}
};
class Sub: public OperateTmp
{
public:
double GetResult()
{
return numA - numB;
}
};
class OperateFactory
{
public:
static OperateTmp* create(char operCh)
{
if(operCh == '+')
{
return new Add();
}
else if(operCh == '-')
{
return new Sub();
}
return NULL;
}
};
int main()
{
double numA(0.0),numB(0.0);
char OperCh;
scanf("%lf %lf %c",&numA,&numB,&OperCh);
OperateTmp* oper = OperateFactory::create(OperCh);
if(oper)
{
oper->numA = numA;
oper->numB = numB;
printf("%lf",oper->GetResult());
delete oper;
oper = NULL;
}
return 0;
}