Liskov替代原则-没有覆盖/虚拟方法? [英] Liskov substitution principle - no overriding/virtual methods?

查看:98
本文介绍了Liskov替代原则-没有覆盖/虚拟方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Liskov替换原理的理解是,对派生类而言,基类的某些正确属性或基类的某些已实现行为也应为真.

My understanding of the Liskov substitution principle is that some property of the base class that is true or some implemented behaviour of the base class, should be true for the derived class as well.

我想这意味着在基类中定义方法时,永远不要在派生类中重写该方法,因为用基类代替派生类将产生不同的结果.我想这也意味着拥有(非纯)虚拟方法是一件坏事吗?

I guess this would mean when a method is defined in a base class, it should never be overrided in the derived class - since then substituting the base class instead of the derived class would give different results. I guess this would also mean, having (non-pure) virtual methods is a bad thing?

我认为我可能对该原理有错误的理解.如果我不这样做,我将不明白为什么这个原则是好的做法.谁可以给我解释一下这个?谢谢

I think I might have a wrong understanding of the principle. If I don't, I do not understand why is this principle good practice. Can someone explain this to me? Thanks

推荐答案

Liskov替换原理完全允许基类中的子类重写方法.

Subclasses overriding methods in the base class are totally allowed by the Liskov Substituion Principle.

这可能会使它简化太多,但我记得它是 子类应只要求更多,而应承诺不得多"

This might be simplifying it too much, but I remember it as "a subclass should require nothing more and promise nothing less"

如果客户端将超类ABC与方法something(int i)一起使用,则客户端应该可以替换ABC的任何子类而不会出现问题.与其从变量类型的角度来考虑,不如从前置条件和后置条件来考虑.

If a client is using a superclass ABC with a method something(int i), then the client should be able to substitute any subclass of ABC without problems. Instead of thinking about this in terms of variable types, perhaps think about it in terms of preconditions and postconditions.

如果上面ABC基类中的something()方法具有宽松的前提,允许 any 整数,则ABC 必须的所有子类也都允许任何整数.不允许子类GreenABCsomething()方法添加附加的前提条件,该前提条件要求参数为整数.这将违反《里斯科夫换人原则》(即要求更多).因此,如果客户端使用子类BlueABC并将负整数传递给something(),则如果我们需要切换到GreenABC,客户端将不会中断.

If our something() method in the ABC base class above has a relaxed precondition that permits any integer, then all subclasses of ABC must also permit any integer. A subclass GreenABC is not allowed to add an additional precondition to the something() method that requires the parameter to be a positive integer. This would violate the Liskov Substitution Principle (i.e., requiring more). Thus if a client is using subclass BlueABC and passing negative integers to something() the client won't break if we need to switch to GreenABC.

相反,如果基本ABCsomething()方法具有后置条件(例如,保证其绝不会返回零值),则所有子类也必须遵守相同的后置条件,否则它们将违反Liskov替代原理(即承诺更少).

In reverse, if the base ABC class something() method has a postcondition - such as guaranteeing it will never return a value of zero - then all subclasses must also obey that same postcondition or they violate the Liskov Substitution Principle (i.e., promising less).

我希望这会有所帮助.

这篇关于Liskov替代原则-没有覆盖/虚拟方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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