一. Operation基类
class Operation
{
private:
double _numberA = 0.0f;
double _numberB = 0.0f;
public:
void SetNumberA(double A) { _numberA = A; }
void SetNumberB(double B) { _numberB = B; }
double GetNumberA() { return _numberA; }
double GetNumberB() { return _numberB; }
public:
virtual double GetResult();
};
double Operation::GetResult()
{
double result = 0;
return result;
}
二. 算法子类
class Operation_Add :public Operation
{
public:
double GetResult() override
{
double result = 0;
result = GetNumberA() + GetNumberB();
return result;
}
};
class Operation_Sub :public Operation
{
public:
double GetResult() override
{
double result = 0;
result = GetNumberA() - GetNumberB();
return result;
}
};
class Operation_Mul :public Operation
{
public:
double GetResult() override
{
double result = 0;
result = GetNumberA() * GetNumberB();
return result;
}
};
class Operation_Div :public Operation
{
public:
double GetResult() override
{
double result = 0;
double numberB = GetNumberB();
if (numberB == 0) {
std::cout << "除数不能为0," << std::endl;
return result;
}
result = GetNumberA() / GetNumberB();
return result;
}
};
三. 运算工厂类
class OperationFactory
{
public:
static Operation* createOperation(char operate)
{
Operation* oper = nullptr;
switch (operate)
{
case '+':
oper = new Operation_Add();
break;
case '-':
oper = new Operation_Sub();
break;
case '*':
oper = new Operation_Mul();
break;
case '/':
oper = new Operation_Div();
break;
default:
break;
}
return oper;
}
};
四. 运算工厂类的使用
#include
#include
#include
#include
#include "OperationFactory.h"
using namespace std;
int main()
{
string strNumberA;
cout << "请输入数字A:";
cin >> strNumberA;
string strOperator;
cout << "请输入运算符号(+、-、*、/):";
cin >> strOperator;
string strNumberB;
cout << "请输入数字B:";
cin >> strNumberB;
Operation* oper = OperationFactory::createOperation(strOperator[0]);
oper->SetNumberA(atof(strNumberA.c_str()));
oper->SetNumberB(atof(strNumberB.c_str()));
double dResult = oper->GetResult();
cout << "结果是:" << std::to_string(dResult) << endl;
}
*概念: 定义一个用于创建对象的接口,由子类决定实例化那个类的对象;
*优点:a. 没有了将应用程序类绑定到代码中的要求,代码只处理接口,因此可以使用任何实现了的接口的类;
b.允许子类提供对象的扩展版本;
c. 符合迪米特法则、依赖倒置原则、里氏替换原则。
*缺点:a. 需要Creator和相应的子类作为工厂方法的载体,如果应用模型确实需要creator和子类存在,则很好,否则需要增加一个类层次。
*适用场景:a. 当一个类不知道它所创建的产品的具体是那个子类时;
b. 当创建的对象的过程希望延缓到子类中进行时;
c. 当希望子类指定它要创建的对象。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)