目录
代码记录
设计模式的代码注意要运用到面向对象的思想 考虑到紧耦合和松耦合
把具体的操作类分开 不让其互相影响(注意这点)
下面是UML类图
代码部分
#include <iostream>
#include <memory> // 引入智能指针的头文件
using namespace std;
// 操作基类
class Operate {
public:
Operate() {}
virtual ~Operate() {}
virtual int GetResult() = 0; // 纯虚函数,强制派生类实现
void SetNumsA(int A)
{
NumsA = A;
}
void SetNumsB(int B)
{
NumsB = B;
}
protected:
int NumsA, NumsB;
};
// 加法操作类
class AddOperate : public Operate {
public:
int GetResult() override {
return NumsA + NumsB;
}
};
// 减法操作类
class SubOperate : public Operate {
public:
int GetResult() override {
return NumsA - NumsB;
}
};
// 乘法操作类
class MulOperate : public Operate {
public:
int GetResult() override {
return NumsA * NumsB;
}
};
// 除法操作类
class DivOperate : public Operate {
public:
int GetResult() override {
if (NumsB == 0) {
throw runtime_error("Division by zero is not allowed.");
}
return NumsA / NumsB;
}
};
// 操作工厂类
class OperateFactory {
public:
OperateFactory() {}
std::unique_ptr<Operate> CreateOperate(char op) {
switch (op) {
case '+': return std::make_unique<AddOperate>();
case '-': return std::make_unique<SubOperate>();
case '*': return std::make_unique<MulOperate>();
case '/': return std::make_unique<DivOperate>();
default:
throw runtime_error("No such operation!");
}
}
};
int main() {
try {
OperateFactory factory;
char op = '/';
int numA = 100, numB = 700;
std::unique_ptr<Operate> operate = factory.CreateOperate(op);
operate->SetNumsA(numA);
operate->SetNumsB(0);
cout << operate->GetResult() << endl;
}
catch (const exception& e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}
代码参考书:
大话设计模式