Liskovsubstitution(里氏替换)是oop五原则(SOLID)之一,wikipedia上的介绍如下Substitutabilityisaprincipleinobject-orientedprogramming.Itstatesthat,inacomputerprogram,ifSisasubtypeofT,thenobjectsoftypeTmaybereplacedwithobjectsoftypeS(i.e.,objectsoftypeSmaybesubstitutedforobjectsoftypeT)withoutalteringanyofthedesirablepropertiesofthatprogram(correctness,taskperformed,etc.).其中有提到一个比较经典的违反此原则的案例,那就是square和rectangle,先看代码:publicclassRectangle{privatedoublewidth;privatedoubleheight;publicvoidsetWidth(doublewidth){this.width=width;}publicvoidsetHeight(doubleheight){this.height=height;}publicdoublegetHeight(){returnthis.height;}publicdoublegetWidth(){returnthis.width;}publicdoublegetPerimeter(){return2*width+2*height;}publicdoublegetArea(){returnwidth*height;}}publicclassSquareextendsRectangle{publicvoidsetWidth(doublewidth){this.width=width;this.height=width;}publicvoidsetHeight(doubleheight){this.height=height;this.width=height;}}按照自然规则,square是特殊的rectangle(width==height),但是在用两个class来表述时是不符合里氏替换规则的,因为square的setter不满足里氏替换规则里的Postconditionscannotbeweakenedinasubtype。那么到底怎样设计才行呢?
相关分类