为了账号安全,请及时绑定邮箱和手机立即绑定

怎样设计Rectangle和Square类才能使之满足OOP的Liskov substitution原则

怎样设计Rectangle和Square类才能使之满足OOP的Liskov substitution原则

白衣染霜花 2019-04-06 08:31:58
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。那么到底怎样设计才行呢?
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 409 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信