Liskovsubstitution(里氏替換)是oop五原則(SOLID)之一,wikipedia上的介紹如下Substitutabilityisaprincipleinobject-orientedprogramming.Itstatesthat,inacomputerprogram,ifSisasubtypeofT,thenobjectsoftypeTmaybereplacedwithobjectsoftypeS(i.e.,objectsoftypeSmaybesubstitutedforobjectsoftypeT)withoutalteringanyofthedesirablepropertiesofthatprogram(correctness,taskperformed,etc.).其中有提到一個(gè)比較經(jīng)典的違反此原則的案例,那就是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;}}按照自然規(guī)則,square是特殊的rectangle(width==height),但是在用兩個(gè)class來(lái)表述時(shí)是不符合里氏替換規(guī)則的,因?yàn)閟quare的setter不滿足里氏替換規(guī)則里的Postconditionscannotbeweakenedinasubtype。那么到底怎樣設(shè)計(jì)才行呢?
怎樣設(shè)計(jì)Rectangle和Square類(lèi)才能使之滿足OOP的Liskov substitution原則
明月笑刀無(wú)情
2019-04-06 08:31:57