Liskov替代原则是否也适用于实现接口的类? [英] Does Liskov Substitution Principle also apply to classes implementing an interface?

查看:134
本文介绍了Liskov替代原则是否也适用于实现接口的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

LSP表示类可以替代它们的基类,这意味着派生类和基类在语义上是等价的。



但是,LSP也适用于实现接口?换句话说,如果一个类实现的接口方法在语义上与用户期望的不同,那么这被认为是违反LSP的?



谢谢

解决方案



适用于亚型。有关简要摘要,请参阅维基百科文章



如果您有继承或扩展 A类类B ,则应该可以切换 class A with class B ,一切都应该正常工作。接口通常用于不允许多重继承的语言,所以当两个对象共享一个常见的行为时,实际执行所述行为的方式在两者之间是截然不同的,这意味着你不应该可以互换地进行切换。 >

LSP states that classes should be substitutable for their base classes, meaning that derived and base classes should be semantically equivalent.

But does LSP also apply to classes implementing an interface? In other words, if an interface method implemented by a class is semantically different from what user expects it to be, would this be considered as a violation of LSP?

Thank you

解决方案

No

It only applies to subtypes. See the Wikipedia article for a brief summary.

If you have a class B that inherits or extends class A you should be able to switch out class A with class B and everything should work as normal. Interfaces are often used in languages that do not allow for multiple inheritance, so while the two objects share a common behaviour, how that actually execute said behaviour is distinct between both, meaning you shouldn't be able to switch them interchangeably.

这篇关于Liskov替代原则是否也适用于实现接口的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆