里氏替换原则是否适用于从抽象类继承的子类型?

发布于 2024-08-21 02:08:54 字数 84 浏览 7 评论 0原文

宽松地说,里氏替换原则指出派生类可以替换基类而不影响用户。 如果基类是抽象类,这意味着没有用户使用基类的实例,Liskov 继承限制是否仍然适用于派生类?

loosely speaking, Liskov Substitution Principle states that a derived class can be substitute in place of the base class without affecting the user.
In the case when the base class is an abstract class, which means no user is using an instance of the base class, does the Liskov inheritance restrictions still apply to the derived class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

只有一腔孤勇 2024-08-28 02:08:54

仅仅因为您无法实例化特定类并不意味着您无法使用它。在这种情况下,调用代码使用抽象基类作为其操作所依据的合约的定义。从这个意义上说,从基类派生的每个类都应该相对于基类定义的接口是可互换的,所以里氏仍然适用。事实上,这是您希望为具有某些共同行为的类集合提供一个抽象基类的一个主要原因,这样您就可以根据基类接口定义操作,而不必关心哪个派生类是哪个派生类。你实际上正在操作。

Just because you can't instantiate a particular class does not mean that you can't use it. In this scenario, the calling code is using the abstract base class as the definition of the contract under which it operates. In that sense, every class that derives from the base class ought to be interchangable with respect to the interface defined by the base class, so yes Liskov still applies. In fact, this is one primary reason why you would want to have an abstract base class for a collection of classes that have some common behavior -- so you can define operations in terms of the base class interface and not care about which derived class that you are actually operating on.

星星的轨迹 2024-08-28 02:08:54

是的,因为调用者总是可以这样做:

BaseAbstractClass instance = new DerivedClass();

Yes, because a caller can always do this:

BaseAbstractClass instance = new DerivedClass();
彡翼 2024-08-28 02:08:54

抽象类与LSP根本不冲突。许多人认为直接从客户端代码使用“new”违反了 LSP 的精神。如果您既实例化又使用一个对象,那么您将与该实现紧密绑定,并且根本无法“替换”它。

考虑让对象通过工厂创建,或者作为参数传入,或者在由某种类型的存储库创建后通过依赖项注入传递,这些存储库可以专注于决定在各种情况下需要哪些具体类型。

Abstract classes do not conflict with LSP at all. Many people consider using "new" directly from the client code to be a violation of the spirit of LSP. If you both instantiate and use an object, you're tightly-bound to that implementation, and you can't "substitute" it at all.

Consider having the object created via a factory or passed in as an argument or via dependency injection after being created by some kind of repository that can be focused on making decisions about what concrete types are needed in various circumstances.

围归者 2024-08-28 02:08:54

是的。

请参阅 鲍勃叔叔的里氏替换原理文章

来源:旧文章页面 cleancoder.com" rel="nofollow noreferrer">cleancoder.com

Yes.

See the "A Real Example" section (page 7-8) of Uncle Bob's The Liskov Substitution Principle article.

Source: the Old Articles page of cleancoder.com

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文