开闭原则主要概括为:对扩展开放,对修改关闭。
增加功能是通过增加代码实现的,而不是修改源代码。
程序员更喜欢添加类来增加功能,而不是修改源代码。
修改源代码及其容易犯错,若项目文件过大时,类与类的关联性强,改的地方就会特别多。一个类最好只做一件事情。
#include <iostream>
using namespace std;
// 开闭原则, 对扩展开放,对修改关闭,增加功能是通过增加代码来实现,而不是去修改源代码
class AbstractCaculator
{
public:
virtual int getResult() = 0; // 纯虚函数
virtual void setOperatorNumber(int a, int b) = 0;//
// 实现一个虚的析构函数
virtual ~AbstractCaculator()
{
}
};
// 实现加法计算器类
class PlusCaculator:public AbstractCaculator
{
public:
virtual void setOperatorNumber(int a, int b)
{
this->mA = a;
this->mB = b;
};
virtual int getResult()
{
return mA + mB;
}
private:
int mA;
int mB;
};
// 减法计算器类
class MinuteCaculator:public AbstractCaculator
{
public:
virtual void setOperatorNumber(int a, int b)
{
this->mA = a;
this->mB = b;
};
virtual int getResult()
{
return mA - mB;
}
private:
int mA;
int mB;
};
// 乘法计算器类
class MultiplyCaculator:public AbstractCaculator
{
public:
virtual void setOperatorNumber(int a, int b)
{
this->mA = a;
this->mB = b;
};
virtual int getResult()
{
return mA * mB;
}
private:
int mA;
int mB;
};
int main()
{
AbstractCaculator* caculator = new PlusCaculator;
caculator->setOperatorNumber(10, 20);
std::cout << "ret = " << caculator->getResult() << std::endl;
delete caculator;
AbstractCaculator* caculator2 = new MinuteCaculator;
caculator2->setOperatorNumber(10, 20);
std::cout << "ret = " << caculator2->getResult() << std::endl;
delete caculator2;
return 0;
}