设计模式——开闭原则

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

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;
}
相关推荐
blasit3 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
七月丶8 小时前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞8 小时前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼8 小时前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟1 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder1 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星1 天前
虚函数表:C++ 多态背后的那个男人
c++
阿星AI工作室1 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding