设计模式——开闭原则

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

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;
}
相关推荐
Benny_Tang10 小时前
AT_arc180_d [ARC180D] Division into 3 题解
数据结构·c++·算法
殷色玫瑰10 小时前
C++ STL:stack、queue、priority_queue 与容器适配器详解
java·开发语言·数据结构·c++·算法·visualstudio
努力努力再努力wz11 小时前
【CUDA入门系列】CUDA编程实战:设备选择、显存管理、Kernel、Stream 与 Event 全流程梳理
开发语言·c++
沫璃染墨11 小时前
《从零入门Linux系统篇(五十八):线程篇·十一——线程安全与死锁详解:从可重入到多锁管理》
linux·服务器·开发语言·c++·驱动开发·安全·架构
郝学胜_神的一滴11 小时前
C++ Templates 05:那些容易踩坑的技巧性基础知识
c++·visual studio
朝朝辞暮i11 小时前
C++ 第 40 章:ROS2 Publisher + Timer + Subscriber + Callback + Executor 完整闭环
开发语言·c++·算法·ros2
旖旎夜光12 小时前
LeetCode 1576: 替换所有的问号(模拟) —— 题解
c++·学习·算法·leetcode·力控
朝朝辞暮i12 小时前
C++ 第 38 课:线程、SingleThreadedExecutor、MultiThreadedExecutor、Callback Group
开发语言·c++·算法·ros2
(Charon)12 小时前
【C++面试】互斥锁与读写锁:使用场景、实现原理与写饥饿问题
c++·算法
by2099913 小时前
list 的使用:把节点、位置和操作联系起来的综合叙述(上)
数据结构·c++·笔记·list