从GraphNode派生BinaryTreeNode违反了Liskov的替代原理 [英] Is deriving BinaryTreeNode from GraphNode a violation of Liskov's Substitution Princple
问题描述
讨论在这里出现:
问题是:"BTNode扩展GraphNode"设计真的违反了Liskov的Substitution Princeple吗?作为一个类似"的例子,表明了这种情况: 从矩形派生正方形违反了Liskov的替换原理?但是我真的看不出为什么这是相似的.我对设计非常陌生,有人可以向我解释为什么(如果这样)吗?
子类型要求:令ϕ(x)是关于类型T的对象x的可证明性质. ϕ ( ÿ )对于对象应该是正确的 类型S的y,其中S是T的子类型.
简单来说,
如果您可以对T类型执行操作X,那么您也应该可以对T的任何子类执行操作X.
The discussion comes up here:
Changing visibility of method in inherited class
question is: is really "BTNode extends GraphNode" design a violation of Liskov's Substitution Princeple? As an "similar" example it was shown that case: Is deriving square from rectangle a violation of Liskov's Substitution Principle?
but I cannot really see why that is similar. I am very new to design, could someone explain me why (if) that's the case?
In Is deriving square from rectangle a violation of Liskov's Substitution Principle?, it basically says that Square
cannot inherit from Rectangle
because there are things that you can do with Rectangle
s but not with Squares
- setting its width to a different number from its height.
You can't inherit BTNode
from GraphNode
because according to the original post you linked, GraphNode
has a method called addChild
. BTNode
on the other hand, can only have two children. Inheriting from GraphNode
will also inherit the addChild
method. This allows you to add multiple children to BTNode
, which a BTNode
cannot handle.
Therefore, BTNode
cannot inherit from GraphNode
because there are things that you can do with GraphNode
s but not with BTNode
s - adding multiple children.
For completeness, here is the Liskov's Substitution principle from Wikipedia
Subtype Requirement: Let ϕ(x) be a property provable about objects x of type T. Then ϕ ( y ) should be true for objects y of type S where S is a subtype of T.
In simple terms,
If you can do action X on type T, you should also be able to do action X on any subclasses of T.
这篇关于从GraphNode派生BinaryTreeNode违反了Liskov的替代原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!