本文介绍了从GraphNode派生BinaryTreeNode违反了Liskov的替代原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

讨论在这里出现:

更改继承类中方法的可见性

问题是:"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 Rectangles 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 GraphNodes but not with BTNodes - adding multiple children.

For completeness, here is the Liskov's Substitution principle from Wikipedia

In simple terms,

这篇关于从GraphNode派生BinaryTreeNode违反了Liskov的替代原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 07:51