设计模式01-减少修改代码的开闭原则


一、开闭原则概念

开闭原则:对扩展开放,对修改关闭

  • 增加功能应该是增加代码而不应该是修改代码

通常用在需要功能扩展的应用场景中。

二、例子

#include <iostream>
#include <string>
using namespace std;

class Calculator {
public:
	Calculator(int a, int b, string how2operator) {
		this->_a = a;
		this->_b = b;
		this->_operator = how2operator;
	}

	int GetRes() {
		if (_operator == "+") {
			return _a + _b;
		}
		else if (_operator == "-") {
			return _a + _b;
		}
		else if (_operator == "*") {
			return _a * _b;
		}
		else if (_operator == "/") {
			return _a / _b;
		}
		else {
			return -1;
		}
	}
private:
	int _a;
	int _b;
	string _operator;
};

void test() {
	Caculator* c = new Calculator(1, 2, "+");
	cout << c->GetRes() << endl;
	delete c;
}

int main() {

	test();
	return 0;
}

在上面的例子中,我们新建了一个 Caculator 类,在构造函数中通过操作数和操作符构造 Caculator 类的对象,并通过 GetRes 方法来返回计算结果。

这样的代码存在一些问题,如果我们需要添加一个取模运算,就需要在 GetRes 方法中加入取模运算符的判断,这样比较容易出现问题。

解决的办法是,通过一个抽象类定义统一的接口 GetRes,然后定义不同的计算器类来继承这个抽象类。

#include <iostream>
#include <string>
using namespace std;

class AbstractCalculator {
public:
	virtual int GetRes() = 0;
	virtual void Init(int a, int b) = 0;
};

class plusCalculator : public AbstractCalculator {
public:
	void Init(int a, int b) override {
		this->_a = a;
		this->_b = b;
	}

	virtual int GetRes() override {
		return _a + _b;
	}
private:
	int _a;
	int _b;
};

void test() {
	AbstractCalculator* c = new plusCalculator;
	c->Init(1, 2);
	cout << c->GetRes() << endl;
	delete c;
}

int main() {

	test();
	return 0;
}

这样,当我们想增加计算方法时只要增加计算方法的类即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值