Circle-Ellipse Problem 中有一个违反里氏替换原则的好例子。 .
这是 a popular SO answer 中的表述方式(尽管是用矩形和正方形表示) :
In mathematics, a
Square
is aRectangle
. Indeed it is a specialization of a rectangle. The "is a" makes you want to model this with inheritance. However if in code you madeSquare
derive fromRectangle
, then aSquare
should be usable anywhere you expect aRectangle
. This makes for some strange behavior.Imagine you had
SetWidth
andSetHeight
methods on your Rectangle base class; this seems perfectly logical. However if your Rectangle reference pointed to aSquare
, thenSetWidth
andSetHeight
doesn't make sense because setting one would change the other to match it. In this case Square fails the Liskov Substitution Test withRectangle
and the abstraction of having Square inherit from Rectangle is a bad one.
我的问题是 - 给定一个解决方案,我们使用设置 width
的实现来覆盖 Square
中的 setWidth
> 和 height
为相同的值,为什么仍然违反 LSP?
最佳答案
它确实违反了它,因为您 promise setWidth()
将设置宽度,而 setHeight()
将设置高度。 Square
将打破 Rectangle
做出的这一(隐式) promise 。
关于oop - 为什么 "Circle-ellipse"的这个解决方案违反了 "Liskov Substition Principle"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49220013/