gpt4 book ai didi

oop - 反射是否违反了 LSP?

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

来自 Liskov Substitution Principle - www.blackwasp.co.uk

One common indication of non-compliance with the LSP is when a client class checks the type of its dependencies. This may be by reading a property of an object that artificially describes its type or by using reflection to obtain the type. Often a switch statement will be used to perform a different action according to the type of the dependency. This additional complexity also violates the Open / Closed Principle (OCP), as the client class will need to be modified as further subclasses are introduced.

以下技术(使用反射)是否会导致违反 LSP?

  1. 依赖注入(inject)
  2. 控制反转

注意:我来自 C# 背景。

来自 http://blogs.msdn.com/b/simonince/archive/2008/06/30/dependency-injection-is-dead.aspx

Reflection; most (perhaps all?) Dependency Injection containers rely on some extent on Reflection – dynamically inspecting objects and determining their dependencies.

引用资料:

  1. Hierarchy violates Liskov - so what?

  2. How can I avoid breaking Liskov Substitution Principle (LSP)?

  3. Does Liskov Substitution Principle also apply to classes implementing an interface?

  4. Does this violate the Liskov substitution principle, and if so, what do I do about it?

  5. Does GWT's ActivityMapper violate the Liskov Substitution Principle?

最佳答案

我对 LSP 的理解是,它只是说明子类在任何情况下都应该可以替代它们的基类,也就是说,每当您将基类的实例传递给方法、构造函数、服务等时。 .) 您应该能够传递子类的实例,而无需任何代码修改才能使其正常工作。与任何其他原则一样,LSP 是一个指南而非严格的规则,它使我们的代码更易于扩展。当框架编写者使用反射时,他们并没有破坏 LSP,您可以简单地将其与使用 Service Location 的框架进行对比。许多 OO 支持者现在认为这是一种反模式,但他们必须这样做,因此他们的框架让您可以选择自己的容器。一如既往,这是一个权衡,它取决于上下文(自己的特定用例)

关于oop - 反射是否违反了 LSP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17185651/

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