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。那么到底怎樣設計才行呢?
怎樣設計Rectangle和Square類才能使之滿足OOP的Liskov substitution原則
明月笑刀無情
2019-04-06 08:31:57