OCP(Open-Closed Principle),通常認(rèn)為是Bertrand Meyer在1988年在《Object Oriented Software Construction》
里提出來的。
簡單來說,OCP的內(nèi)容是:程序中的實(shí)體(類、函數(shù)等)需要對(duì)擴(kuò)展開放(open for extensions),而對(duì)修改封閉(closed for modifications)。
Server-Client問題
在C++中,我們可以使用抽象類(java中是接口),設(shè)想如下情景:有一個(gè)Client類和一個(gè)Server類,Client依賴于Server:
class Server
{
public void balabala(){}
}
class Client
{
private server __serv;
public Client(Server serv)
{
__serv = serv
}
}
那么如果我們需要擴(kuò)展Client的行為,讓它對(duì)接更多的Server,就不得不修改Client的代碼,這是不符合OCP原則的。
而使用抽象類和純虛函數(shù),就可以不對(duì)Client進(jìn)行任何修改而對(duì)接任何繼承了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
}
}
當(dāng)然任何稍微有點(diǎn)經(jīng)驗(yàn)的程序員必然經(jīng)常以類似這樣的形式構(gòu)建代碼,可以說幾乎是本能了,只是早在1988年,甚至連java都還沒出世的時(shí)候,已經(jīng)有人做過了系統(tǒng)的總結(jié)。
圖形繪制問題
設(shè)想這樣一個(gè)應(yīng)用:需要在屏幕上繪制圓形或者矩形,繪制順序在一個(gè)隊(duì)列里,按照隊(duì)列順序繪制。
一個(gè)不符合OCP的設(shè)計(jì)如下:
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;
}
}
}
那么當(dāng)我想擴(kuò)展DrawAllShapes的功能的時(shí)候,我就會(huì)需要修改DrawAllShapes函數(shù)的內(nèi)容,這是違背了OCP原則的。
當(dāng)然哪怕是入門級(jí)的初學(xué)者都知道這時(shí)候要用純虛函數(shù),讓派生類各自實(shí)現(xiàn)一個(gè)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();
}
}
如此,只要通過擴(kuò)展派生類就可以實(shí)現(xiàn)繪制不同的圖形而不需要修改DrawAllShapes函數(shù)。
戰(zhàn)略性封閉
即使如此,我們依舊不可能完全預(yù)先實(shí)現(xiàn)DrawAllShapes的所有需求,修改總是難以避免的,但是戰(zhàn)略上,我們需要在OCP原則指導(dǎo)下進(jìn)行修改,比如要對(duì)DrawAllShapes實(shí)現(xiàn)一個(gè)排序,讓Circle總是在Square之前進(jìn)行繪制,如果直接實(shí)現(xiàn)一個(gè)排序函數(shù):
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,看起來很好,簡單的排序算法就能實(shí)現(xiàn)了,但是如果派生了新的類型呢?每個(gè)新的形狀都要導(dǎo)致所有其它形狀修改operator<,使新的形狀有一個(gè)合適的排序位置,這很不OCP,此時(shí)我們就需要加入“數(shù)據(jù)驅(qū)動(dòng)”,創(chuàng)建一個(gè)數(shù)組存儲(chǔ)派生類們的排序:
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中添加一個(gè)新字符串而已。
總結(jié)
OCP原則可以說是跟多態(tài)息息相關(guān)的,C++多態(tài)的存在就是為了盡量減少重復(fù)工作,而OCP原則就是能更好地利用多態(tài)的指導(dǎo)思想,但是在設(shè)計(jì)程序的時(shí)候不可能保證任何公共部分都不需要修改,因?yàn)樾枨罂偸菚?huì)變動(dòng),只是在修改的時(shí)候要時(shí)刻記住在當(dāng)前需求下,一定要滿足OCP原則。