这是对Liskov替代原理的正确理解吗 [英] Is this correct understanding of Liskov Substitution Principle
问题描述
这是在采访中问我的.
我回答他说,对于相同的输入集,父母和孩子都应产生相同的输出集.如果孩子想扩展父母的功能,则只能对父母支持的范围以外的新输入进行操作.这样,孩子将维持其父母签订的合同.
I answered him by saying that for same set of input both parent and child should produce same set of output. If child wants to extend parent's functionality it should do only on new inputs outside the range supported by parent. In that way, child will maintain the contract made by it's parent.
我举了一个例子,一个api可能正在使用像这样的父母
I gave him example, that an api may be using a parent like this
if(parent.getOutput(10) == 5){/*do something */}
如果孩子在这里产生了不同的输出,则表明该孩子违反了其父母的合同.
If child produced a different output here then that child has broken the contract made by it's parent.
他对我的回答不满意,并告诉我这是简单的重写,并不违反LSP. 所以,我只是想确认一下,如果我理解正确的话.
He wasn't satisfied with my answer and told me that this is simple overriding and is not a violation of LSP. So, I just want to confirm, if i understand this correct.
推荐答案
不,这是不正确的.
《里斯科夫替代原则》的要点是,根据相关合同,子类应能够与父类以相同的方式使用.对于相同的输入,不需要产生相同的输出.
The point of the Liskov Substitution Principle is that a child class should be able to be used in the same manner as the parent class, according to relevant contracts. It does not need to produce identical output for identical input.
在不可避免的动物主题中,下面是一个示例,其中方法为相同的输入返回不同的输出:
In the inevitable animal theme, here's an example where the methods return different outputs for the same input:
class Dog {
String getNoise() {
return "WOOF WOOF!!!"
}
}
class FrenchBulldog extends Dog {
String getNoise() {
return "mrfff!"
}
}
FrenchBulldog
可以在任何上下文中代表任何Dog
,并且行为相同,因此不违反LSP.
FrenchBulldog
can stand in for any Dog
in any context and behaves in the same manner, and it's therefore not a violation of the LSP.
如果您改为创建类似这样的内容:
If you instead create something like this:
class Hotdog extends Dog implements Edible {
String getNoise() {
throw new NotImplementedException("I am actually a sausage");
}
String eat() {
return "Delicious";
}
}
然后它就不能再代表Dog
.与Dog
和FrenchBulldog
完美配合的代码不再具有应有的功能.任何狗美容师或狗窝都知道该做什么,而不管狗发出的噪音如何,但是如果您带上热狗会很困惑.这 违反了LSP.
then it can no longer stand in for a Dog
. Code that works perfectly with Dog
s and FrenchBulldog
s no longer behaves the way it should. Any dog groomer or kennel knows what to do regardless of the noise the Dog makes, but will be very confused if you bring a Hotdog. This is a violation of LSP.
这篇关于这是对Liskov替代原理的正确理解吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!