开闭原则:
对扩展开放,对修改关闭。
增加功能是提过增加代码来实现的,而不是去修改源代码。
代码如下:
#include <iostream>
#include <string>
using namespace std;class Caculaor
{
public:Caculaor(int a,int b,string c):a(a),b(b),myOperator(c){}int getResult(){if (myOperator.compare("+") == 0){return a + b;}else if (myOperator.compare("-") == 0){return a - b;}else if (myOperator.compare("*")==0){return a * b;}else if (myOperator.compare("/") == 0){return a / b;}}private:int a;int b;string myOperator;
};void test01()
{Caculaor *a = new Caculaor(10, 10, "+");cout<<a->getResult()<<endl;
}int main()
{test01();return 0;
}
测试结果:
缺点:
如果增加取模的运算,需要修改getResult成员方法,如果增加新功能的情况下要修改源代码,那么就会有出错的可能性,我们应该在增加新的功能时候,不能影响其他已经完成的功能,这就是对修改关闭,对扩展开放,叫做开闭原则。
开闭原则
代码如下:
#include <iostream>
#include <string>
using namespace std;class AbstractCaculator {
public:virtual int getResult() = 0;virtual void setNumber(int a, int b) = 0;
};class PlusCaculator :public AbstractCaculator
{
public:virtual void setNumber(int a, int b){this->a = a;this->b = b;}virtual int getResult(){return a + b;}private:int a;int b;
};class MinuteCaculator :public AbstractCaculator
{
public:virtual void setNumber(int a, int b){this->a = a;this->b = b;}virtual int getResult(){return a - b;}private:int a;int b;
};class MultiplyCaculator :public AbstractCaculator
{
public:virtual void setNumber(int a, int b){this->a = a;this->b = b;}virtual int getResult(){return a * b;}private:int a;int b;
};class DivideCaculator :public AbstractCaculator
{
public:virtual void setNumber(int a, int b){this->a = a;this->b = b;}virtual int getResult(){return a / b;}private:int a;int b;
};//取模计算器 通过增加代码来实现
class MoldTakingCaculator :public AbstractCaculator
{
public:virtual void setNumber(int a, int b){this->a = a;this->b = b;}virtual int getResult(){return a % b;}private:int a;int b;
};void test01()
{AbstractCaculator *a = new PlusCaculator;a->setNumber(10, 10);cout << a->getResult() << endl;
}int main()
{test01();return 0;
}
测试结果: