1.运算类
class Operation
{
public:
virtual double GetResult(double Num1, double Num2)
{
return 0;
}
};
2.加减乘除类
class OperationAdd : public Operation
{
virtual double GetResult(double Num1, double Num2)
{
return Num1 + Num2;
}
};
class OperationSub : public Operation
{
virtual double GetResult(double Num1, double Num2)
{
return Num1 - Num2;
}
};
class OperationMul : public Operation
{
virtual double GetResult(double Num1, double Num2)
{
return Num1 * Num2;
}
};
class OperationDiv : public Operation
{
virtual double GetResult(double Num1, double Num2)
{
if(Num2 == 0)
{
throw new exception("除数不能为0");
}
return Num1 / Num2;
}
};
3.运算工厂
class OperationFactory
{
public:
static Operation* CreateOperation(char OperationType)
{
switch(OperationType)
{
case '+':
return new OperationAdd();
case '-':
return new OperationSub();
case '*':
return new OperationMul();
case '/':
return new OperationDiv();
}
return NULL;
}
};
4.客户端代码
int main()
{
Operation *Oper = OperationFactory::CreateOperation('*');
double result = Oper->GetResult(2, 5);
std::cout << "result = " << result << std::endl;
return 0;
}