从 Graph Node 派生 BinaryTreeNode 是否违反了 Liskov Substitution Principle

Is deriving BinaryTreeNode from GraphNode a violation of Liskov's Substitution Princple

讨论出现在这里:

问题是:真的"BTNode extends GraphNode"设计违反了Liskov's Substitution Princeple吗?作为 "similar" 示例,显示了这种情况: Is deriving square from rectangle a violation of Liskov's Substitution Principle?

但我真的不明白为什么这很相似。我是设计新手,有人可以解释一下为什么(如果)是这样吗?

Is deriving square from rectangle a violation of Liskov's Substitution Principle?中,它基本上说Square不能继承自Rectangle 因为有些事情你可以用Rectangle做但是不适用于 Squares - 将其宽度设置为与其高度不同的数字。

您不能从 GraphNode 继承 BTNode,因为根据您链接的原始 post,GraphNode 有一个名为 addChild 的方法。 BTNode 另一方面,只能有两个 children。继承自 GraphNode 也会继承 addChild 方法。这允许您将多个 children 添加到 BTNode,这是 BTNode 无法处理的。

因此,BTNode 不能继承自 GraphNode ,因为有些事情可以用 GraphNode 做,但不能用 BTNodes - 添加多个 children.

为了完整起见,这里是来自 Wikipedia

的 Liskov 替换原则

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.

简单来说,

If you can do action X on type T, you should also be able to do action X on any subclasses of T.