开闭原则

shienh 2020年01月19日 229次浏览

开闭原则:对扩展开放,对修改关闭。增加功能是通过添加代码实现的,而不是通过修改原有代码实现的。

示例代码:

#include <iostream>
using namespace std;
 
 
class AbstractCalculator{
public:
    virtual int GetResult()=0;
    virtual void SetData(int m,int n)=0;
 
};
 
class Sub:public AbstractCalculator{
public:
    void SetData(int m,int n){
        this->a = m;
        this->b = n;
    }
    int GetResult(){
        return a-b;
    }
private:
    int a;
    int b;
};
 
class Add:public AbstractCalculator{
public:
    void SetData(int m,int n){
        this->a = m;
        this->b = n;
    }
    int GetResult(){
        return a+b;
    }
private:
    int a;
    int b;
};
 
 
int main(int argc, char *argv[])
{
    AbstractCalculator* sub = new Sub();
    sub->SetData(5,3);
    int ret = sub->GetResult();
    cout<<ret<<endl;
    delete sub;
 
    AbstractCalculator* add = new Add();
    add->SetData(5,3);
    ret = add->GetResult();
    cout<<ret<<endl;
    delete add;
 
    return 0;
}