• 对扩展开放,对修改关闭
  • 类模块应该是可扩展的,但是不可修改源代码

如下所示,如果想要扩展乘法、除法、取模等算法,就不用修改原码,只需增加新类

class AbstractCalculator{
public:
    virtual void setOperatorNum(int a, int b) = 0;
    virtual int getResult() = 0;
};
class PlusCalculator:public AbstractCalculator{
public:
    void setOperatorNum(int a, int b)override{
        m_a = a;
        m_b = b;
    }
    int getResult()override{
        return m_a + m_b;
    }
private:
    int m_a{0};
    int m_b{0};
};
class MinusCalculator:public AbstractCalculator{
public:
    void setOperatorNum(int a, int b)override{
        m_a = a;
        m_b = b;
    }
    int getResult()override{
        return m_a - m_b;
    }
private:
    int m_a{0};
    int m_b{0};
};
int main()
{
    AbstractCalculator* calculator = new PlusCalculator;
    calculator->setOperatorNum(10, 20);
    cout << calculator->getResult() << endl;
    delete calculator;
    calculator = nullptr;
    calculator = new MinusCalculator;
    calculator->setOperatorNum(10, 20);
    cout << calculator->getResult() << endl;
    delete calculator;
    calculator = nullptr;
    
    return 0;
}