大话设计模式c++实现1——简单工厂模式 Simple Factory Pattern

时间:2022-03-06 21:49:02

问题:实现一个计算器控制台程序。

编程初学者会直觉地用计算机能够理解的逻辑来描述和表达解决问题的具体求解过程,这其实是用计算机的方式去思考。比如计算器程序,小要求输入两个数和运算符号,然后根据运算符号判断选择如何运算,得到结果。想法本身没问题,但这样的程序不易于维护,不容易扩展,更不容易复用。

面向对象的好处就如同活字印刷和雕版印刷的区别一样:1.可维护,2.可复用, 3.可扩展, 4.灵活性好。

面向对象的三个特征是:封装、继承、多态。

技巧:变复制为复用、业务逻辑与界面逻辑分开

简单工厂模式:将来有可能继续增加实例化的对象,如计算器增加开方运算等等,这个时候考虑单独用一个类来做这个创造实例的过程,这就是工厂

计算器程序运用简单工厂模式,水平有限,很多地方以后知识上来之后再进行改进:

大话设计模式c++实现1——简单工厂模式 Simple Factory Pattern

#include <iostream>
using namespace std;

//运算类
class Operation
{
private:
double _numberA = 0;
double _numberB = 0;
public:
double GetNumberA() { return _numberA; }
void SetNumberA(double numA) { _numberA = numA; }
double GetNumberB() { return _numberB; }
void SetNumberB(double numB) { _numberB = numB; }
virtual double GetResult()
{
double result = 0;
return result;
}
};
//加减乘除类
class OperationAdd : public Operation
{
public:
double GetResult() override
{
double result = 0;
result = GetNumberA() + GetNumberB();
return result;
}
};
class OperationSub : public Operation
{
public:
double GetResult() override
{
double result = 0;
result = GetNumberA() - GetNumberB();
return result;
}
};
class OperationMul : public Operation
{
public:
double GetResult() override
{
double result = 0;
result = GetNumberA() * GetNumberB();
return result;
}
};
class OperationDiv : public Operation
{
public:
double GetResult() override
{
double result = 0;
if (GetNumberB() == 0.0)
cout << "除数不能为0!" << endl;; //预留异常处理
result = GetNumberA() / GetNumberB();
return result;
}
};

//简单运算工厂类
class OperationFactory
{
public:
static Operation* createOperate(char operate)
{
Operation* oper = nullptr;
switch (operate)
{
case '+':
oper = new OperationAdd();
break;
case '-':
oper = new OperationSub();
break;
case '*':
oper = new OperationMul();
break;
case '/':
oper = new OperationDiv();
break;
}
return oper;
}
};

int main()
{
Operation* oper;
oper = OperationFactory::createOperate('/');
if (oper == nullptr)
return -1;
oper->SetNumberA(10);
oper->SetNumberB(0);
double result = oper->GetResult();
std::cout << result << endl;
delete oper;
oper = nullptr;

system("pause");
return 0;
}