设计模式——开闭原则

如今想设计这样的一个计算器类,对提交上来的数据进行运算并返回结果:

cpp 复制代码
class calculation
{
public:
	calculation(int a, int b, string op) :_a(a), _b(b), _op(op)
	{};
	int getret()
	{
		if (_op == "+")
			return _a + _b;
		if (_op == "-")
			return _a - _b;
		if (_op == "*")
			return _a * _b;
		if (_op == "/")
			return _a / _b;
	}
private:
	int _a;
	int _b;
	string _op;
	int _ret = 0;
};
void test()
{
	calculation* ca1 = new calculation(1, 1, "+");
	cout << ca1->getret()<<endl;
	calculation* ca2 = new calculation(1, 1, "*");
	cout << ca2->getret()<<endl;
}
int main()
{
	test();
	return 0;
}

但是这段代码存在问题:如果想对该计算器类增添新的功能,比如说取余或者开方等等。那么就需要修改函数内的代码,这样就导致了一个问题:我们在修改代码的时候可能会出错,导致一系列后果,这就是所谓的高耦合。但是我们想到的是低耦合的代码。所以可以将不同的运算分别写在一个类中。这样就避免了上述问题:

cpp 复制代码
#include<iostream>
using namespace std;
class getretClass
{
	virtual int getret() = 0;
};
class Plus:public getretClass
{
public:
	Plus(int a, int b) :_a(a), _b(b) {};
	virtual int getret()
	{
		return _a + _b;
	}
private:
	int _a;
	int _b;
};
class Minus:public getretClass
{
public:
	Minus(int a, int b) :_a(a), _b(b) {};
	virtual int getret()
	{
		return _a - _b;
	}
private:
	int _a;
	int _b;
};
// 其他运算省略了
void test()
{
	Plus* plus = new Plus(1, 2);
	cout << plus->getret() << endl;
	Minus* minus = new Minus(2, 1);
	cout << minus->getret() << endl;
}
int main()
{
	test();
	return 0;
}
相关推荐
寻星探路36 分钟前
【算法专题】滑动窗口:从“无重复字符”到“字母异位词”的深度剖析
java·开发语言·c++·人工智能·python·算法·ai
我叫袁小陌1 小时前
C++多线程全面详解
开发语言·c++
m0_748250032 小时前
C++ 官方文档与标准
开发语言·c++
matlabgoodboy2 小时前
程序代做python代编程matlab定制代码编写C++代写plc设计java帮做
c++·python·matlab
魅影骑士00102 小时前
柯里化函数
后端·设计模式
DYS_房东的猫2 小时前
《 C++ 零基础入门教程》第6章:模板与 STL 算法 —— 写一次,用万次
开发语言·c++·算法
点云SLAM3 小时前
C++ 静态初始化顺序问题(SIOF)和SLAM / ROS 工程实战问题
开发语言·c++·slam·静态初始化顺序问题·工程实战技术·c++static 关键字
pen-ai3 小时前
打通 Python 与 C++ 的参数传递机制
开发语言·c++·python
王老师青少年编程4 小时前
信奥赛C++提高组csp-s之KMP算法详解
c++·kmp·字符串匹配·csp·信奥赛·csp-s·提高组
喵星人工作室4 小时前
C++传说:神明之剑0.4.5装备机制彻底完成
开发语言·c++·游戏