开闭原则是一种开发原则,表述为
对拓展进行开放,对修改进行关闭。
也就是对拓展功能进行开放,但是修改代码时不被允许,源代码具有拓展性,那么就可以直接进行拓展,不建议修改源码。
例如下面的计算机案例
#include <iostream>
#include <string>
using namespace std;
class Calculator {
public:
int getResult(string optr) {
if (optr == "+") {
return m_Num1 + m_Num2;
}
else if (optr == "-") {
return m_Num1 - m_Num2;
}
else if (optr == "*") {
return m_Num1 * m_Num2;
}
else return 0;
}
int m_Num1;
int m_Num2;
};
void example() {
Calculator c1;
c1.m_Num1 = 2;
c1.m_Num2 = 3;
cout << c1.m_Num1 << "+" << c1.m_Num2 << "=" << c1.getResult("+") << endl;
}
int main() {
example();
return 0;
}
上面的案例中,每次增加功能时,都必须要更改类。而且对源码的更改涉及到数据结构的变化,不符合开闭原则。
那么就需要用多态来实现将计算机作为总体抽象出来,然后再具体添加功能类。
#include <iostream>
#include <string>
using namespace std;
class AbstractCalculator {
public:
virtual int getResult() {
return 0;
}
int m_Num1;
int m_Num2;
};
class Add :public AbstractCalculator {
public:
int getResult() {
return m_Num1 + m_Num2;
}
};
class miu :public AbstractCalculator {
public:
int getResult() {
return m_Num1 - m_Num2;
}
};
class mul :public AbstractCalculator {
public:
int getResult() {
return m_Num1 * m_Num2;
}
};
void example() {
AbstractCalculator *Calc = new Add;
Calc->m_Num1 = 10;
Calc->m_Num2 = 20;
cout << Calc->m_Num1 << "+" << Calc->m_Num2 << "=" << Calc->getResult()<< endl;
delete Calc;
Calc = new miu;
Calc->m_Num1 = 40;
Calc->m_Num2 = 10;
cout << Calc->m_Num1 << "-" << Calc->m_Num2 << "=" << Calc->getResult() << endl;
delete Calc;
Calc = new mul;
Calc->m_Num1 = 4;
Calc->m_Num2 = 5;
cout << Calc->m_Num1 << "*" << Calc->m_Num2 << "=" << Calc->getResult() << endl;
delete Calc;
}
int main() {
example();
return 0;
}
虽然再整体上代码量更高,但是在实际开发场景中,拓展性可读性都将大大增强。
总结:C++开发提倡利用多态设计程序架构,因为多态优点很多