gpt4 book ai didi

oop - 违反里氏替换原则

转载 作者:行者123 更新时间:2023-12-02 08:16:38 26 4
gpt4 key购买 nike

来自 Wikipedia ,

Liskov's notion of a behavioral subtype defines a notion of substitutability for objects; that is, if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program (e.g. correctness).

假设有以下类层次结构:

  1. 基础抽象类 - AnimalWithFur。它有一个只读属性 furColor,在后继者中被覆盖。
  2. 基类的继承者 - Cat,它覆盖 furColor 并返回 gray
  3. Cat 的继任者 - Tiger,它覆盖 furColor 并返回 striped

然后我们用 Cat 类型的参数声明一个方法(不是 AnimalWithFur)。
向该方法发送 Tiger 实例是否违反了 SOLID 中的 L

最佳答案

严格来说,是的。 Liskov 的 wiki 文章总结说:

"...in a program...without altering any of the desirable properties of that program"

如果你回到original paper由芭芭拉·利斯科夫 (Barbara Liskov) 编写,它的措辞 字面上更严格 3.3。类型层次结构:

If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2

(强调我的)

因此,如果您将 Cat 的一个实例替换为另一个执行不同操作的实例,即返回 stripped 而不是 grey,那么这在原始意义上就是 Liskov 违规,因为程序可以很容易地定义依赖于颜色为灰色,这里:

program(Cat c){
println(c.furColor);
}

如果您将 Tiger 替换为 Cat,该程序的行为将会改变

但是,在正常的 LSP 应用方式中,如果您没有添加额外的前置条件或后置条件,则不算违规。这是一个更实际、更不学术的定义,因为人们认为,当用另一种具体类型替换一个具体类型的实例时,您确实打算改变程序的行为,同时保持该程序的理想属性。因此,假设客户端代码可以像任何其他颜色一样处理剥离,并且程序的“理想”属性不需要灰色,那么它就不会违反。

关于oop - 违反里氏替换原则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41384738/

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