gpt4 book ai didi

design-patterns - Square 和 Rectangle 可以继承 Shape,但是 Square 可以继承 Rectangle 吗?

转载 作者:行者123 更新时间:2023-12-04 18:17:09 26 4
gpt4 key购买 nike

你可以有一个父类(super class) Shape,Square 和 Rectangle 是两个子类,但是你可以有 Square 子类 Rectangle,因为 Square 是一个四边相等的特殊 Rectangle?

我试图用一个原则来检验,只要使用父类(super class),它应该可以被它的子类替换,但如果使用子类,它可能无法被它的父类(super class)替换。看起来很好,但我总觉得 Square 不能是 Rectangle 的 child ,因为某种原因?谁能给我一些启示?

最佳答案

您指的是Liskov Substition Principle

Substitutability is a principle in object-oriented programming. It states that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may be substituted for objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.).



具体到您的问题:

A typical example that violates LSP is a Square class that derives from a Rectangle class, assuming getter and setter methods exist for both width and height. The Square class always assumes that the width is equal with the height. If a Square object is used in a context where a Rectangle is expected, unexpected behavior may occur because the dimensions of a Square cannot (or rather should not) be modified independently. This problem cannot be easily fixed: if we can modify the setter methods in the Square class so that they preserve the Square invariant (i.e., keep the dimensions equal), then these methods will weaken (violate) the postconditions for the Rectangle setters, which state that dimensions can be modified independently. Violations of LSP, like this one, may or may not be a problem in practice, depending on the postconditions or invariants that are actually expected by the code that uses classes violating LSP. Mutability is a key issue here. If Square and Rectangle had only getter methods (i.e., they were immutable objects), then no violation of LSP could occur.



用简单的英语 ,您不能在需要 Rectangle 的地方使用 Square,因为 Square 具有 Rectangle 没有的行为。如果有人尝试使用他们认为应该是 Rectangle 的实例,但它实际上是 Square 的实例,他们可能会设置 Width 并惊讶于 Height 自动更改(意外的副作用)。

关于design-patterns - Square 和 Rectangle 可以继承 Shape,但是 Square 可以继承 Rectangle 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11444984/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com