面向对象设计原则——SOLID之OCP

OCP(Open-Closed Principle),通常认为是Bertrand Meyer在1988年在《Object Oriented Software Construction》
里提出来的。
简单来说,OCP的内容是:程序中的实体(类、函数等)需要对扩展开放(open for extensions),而对修改封闭(closed for modifications)。

Server-Client问题

在C++中,我们可以使用抽象类(java中是接口),设想如下情景:有一个Client类和一个Server类,Client依赖于Server:

class Server
{
    public void balabala(){}
}

class Client
{
    private server __serv;
    public Client(Server serv)
    {
        __serv = serv
    }
}

那么如果我们需要扩展Client的行为,让它对接更多的Server,就不得不修改Client的代码,这是不符合OCP原则的。

而使用抽象类和纯虚函数,就可以不对Client进行任何修改而对接任何继承了Server类的特定Server了:

abstract class Server
{
    public void balabala() = 0;
}

class DerivedServer: public Server
{
    public void balabala(){}
}

class Client
{
    private Server* __serv;
    public Client(Server* serv)
    {
        __serv = serv
    }
}

当然任何稍微有点经验的程序员必然经常以类似这样的形式构建代码,可以说几乎是本能了,只是早在1988年,甚至连java都还没出世的时候,已经有人做过了系统的总结。

图形绘制问题

设想这样一个应用:需要在屏幕上绘制圆形或者矩形,绘制顺序在一个队列里,按照队列顺序绘制。

一个不符合OCP的设计如下:

enum ShapeType{ circle,square };

struct Shape{}

struct Circle: public Shape
{
    ShapeType type;
    double radius;
    Point center;
}

struct Square: public Shape
{
    ShapeType type;
    double itsSide;
    Point itsTopLeft;
}

void DrawSquare(struct Square*);
void DrawCircle(struct Circle*);

typedef struct Shape* ShapePointer;

void DrawAllShapes(ShapePointer list[], int n)
{
    int i;
    for(i = 0; i<n; i++)
    {
        struct Shape* s = list[i];
        switch(s->type)
        {
            case ShapeType.square:
                DrawSquare(( struct Square* )s);
                break;
            case ShapeType.circle:
                DrawCircle(( struct Circle* )s);
                break;
        }
    }
}

那么当我想扩展DrawAllShapes的功能的时候,我就会需要修改DrawAllShapes函数的内容,这是违背了OCP原则的。
当然哪怕是入门级的初学者都知道这时候要用纯虚函数,让派生类各自实现一个Draw就是了:

class Shape
{
    public:
        virtual void Draw() = 0;
}

class Circle: public Shape
{
    public:
        void Draw();
}

class Square: public Shape
{
    public:
        void Draw();
}

void DrawAllShapes(Shape* list[],int n)
{
    int i = 0;
    for(; i<n; i++)
    {
        list[i]->Draw();
    }
}

如此,只要通过扩展派生类就可以实现绘制不同的图形而不需要修改DrawAllShapes函数。

战略性封闭

即使如此,我们依旧不可能完全预先实现DrawAllShapes的所有需求,修改总是难以避免的,但是战略上,我们需要在OCP原则指导下进行修改,比如要对DrawAllShapes实现一个排序,让Circle总是在Square之前进行绘制,如果直接实现一个排序函数:

class Shape
{
    public:
        bool operator<(const Shape& shape) = 0;
}

class Square: public Shape
{
    public:
        bool operator<(const Shape& shape)
        {
            if(dynamic_cast<Circle>(shape))
            {
                return true;
            }
            return false;
        }
}

class Circle: public Shape
{
    ...
}

void Sort(Shape* shapes, int n)
{
    for(int i=0; i<n; i++)
    {
        for(int j=i+1; j<n;j++)
        {
                if(shapes[j] < shapes[i])
               {
                   Shape tmp = shapes[i];
                   shapes[i] = shapes[j];
                   shapes[j] = tmp;
               }
        }
    }
}

OK,看起来很好,简单的排序算法就能实现了,但是如果派生了新的类型呢?每个新的形状都要导致所有其它形状修改operator<,使新的形状有一个合适的排序位置,这很不OCP,此时我们就需要加入“数据驱动”,创建一个数组存储派生类们的排序:

class Shape
{
    public:
        static char* typeOrderTable[];
        bool operator<(const Shape other)
        {
                const char* thisType = typeid(*this).name();
                const char* otherType = typeid(other).name();
                int thisOrder = -1;
                int otherOrder = -1;
                for(int i=0; true; i++)
                {
                    if(strcmp(thisType,typeOrderTable[i]) == 0){ thisOrder = i; }
                    if(strcmp(otherType,typeOrderTable[i]) == 0){ otherOrder = i; }
                    if( thisOrder > 0 && otherOrder > 0 ){ return thisOrder < otherOrder; }
                    if( typeOrderTable[i] == 0 ){ return false; }
                }
        }
}

char* Shape::typeOrderTable[] =
{
    "Square",
    "Circle",
    0,
}

如此,每次添加新的形状,便只需要往typeOrderTable中添加一个新字符串而已。

总结

OCP原则可以说是跟多态息息相关的,C++多态的存在就是为了尽量减少重复工作,而OCP原则就是能更好地利用多态的指导思想,但是在设计程序的时候不可能保证任何公共部分都不需要修改,因为需求总是会变动,只是在修改的时候要时刻记住在当前需求下,一定要满足OCP原则。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容