开闭原则(Open

来源:互联网 发布:如何开启3724端口 编辑:程序博客网 时间:2024/06/07 20:24

开闭原则(Open - Closed Principle)

C++ 描述
开闭原则坏的示例,,增加图形的时候GraphicEditor需要变化

class Shape {public:    int m_type;};class Rectangle :public Shape{    Rectangle()    {        Shape::m_type = 1;    }};class Circle :public Shape{    Circle()    {        Shape::m_type = 2;    }};class GraphicEditor {public:    void drawCircle(Shape* r) {  }    void drawRectangle(Shape* r) {  }     void drawShape(Shape* s)      {        if (s->m_type == 1)            drawRectangle(s);        else if (s->m_type == 2)            drawCircle(s);    }};

开闭原则好的示例,增加图形的时候GraphicEditor不用变化

class Shape{public:    virtual void draw()=0;};class Rectangle :public Shape{public:    void draw()    {        // draw the rectangle    }};class Circle :public Shape{public:    void draw()    {        // draw the circle    }};class GraphicEditor {public:    void drawShape(Shape* s)     {        s->draw();    }};
原创粉丝点击