设计模式——开闭原则

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

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;
}
相关推荐
深耕AI1 小时前
MFC + OpenCV 图像预览显示不全中断问题解决:GDI行填充详解
c++·opencv·mfc
余辉zmh1 小时前
【C++篇】:ServiceBus RPC 分布式服务总线框架项目
开发语言·c++·rpc
水饺编程2 小时前
第3章,[标签 Win32] :窗口类03,窗口过程函数字段
c语言·c++·windows·visual studio
千里马-horse2 小时前
在android中 spdlog库的log如何在控制台上输出
android·c++·spdlog
aramae3 小时前
详细分析平衡树--红黑树(万字长文/图文详解)
开发语言·数据结构·c++·笔记·算法
再卷也是菜3 小时前
C++篇(13)计算器实现
c++·算法
_w_z_j_3 小时前
C++----变量存储空间
开发语言·c++
lingran__4 小时前
算法沉淀第五天(Registration System 和 Obsession with Robots)
c++·算法
莱茶荼菜4 小时前
一个坐标转换
c++·算法
guguhaohao4 小时前
list,咕咕咕!
数据结构·c++·list