问题描述
讨论在这里出现:
问题是:"BTNode扩展GraphNode"设计真的违反了Liskov的Substitution Princeple吗?作为一个类似"的例子,表明了这种情况:从矩形派生正方形违反了Liskov的替换原理?但是我真的看不出为什么这是相似的.我对设计非常陌生,有人可以向我解释为什么(如果这样)吗?
在,它基本上说Square
不能从Rectangle
继承,因为您可以做一些事情Rectangle
s,但不包含Squares
-将其宽度设置为与高度不同的数字.
您不能从GraphNode
继承BTNode
,因为根据链接的原始帖子,GraphNode
有一个称为addChild
的方法.另一方面,BTNode
只能有两个孩子.从GraphNode
继承也将继承addChild
方法.这样,您可以将多个子项添加到BTNode
,而BTNode
无法处理.
因此,BTNode
无法从GraphNode
继承,因为有些事情您可以使用GraphNode
进行,而不能使用BTNode
s -添加多个子项.
为完整起见,这是 Wikipedia
中的Liskov替换原则简单来说,
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
In simple terms,
这篇关于从GraphNode派生BinaryTreeNode违反了Liskov的替代原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!