什么是 Liskov 替换原则的例子? [英] What is an example of the Liskov Substitution Principle?
问题描述
我听说 Liskov 替换原则 (LSP) 是面向对象设计的基本原则.它是什么以及它的使用示例有哪些?
I have heard that the Liskov Substitution Principle (LSP) is a fundamental principle of object oriented design. What is it and what are some examples of its use?
推荐答案
一个很好的例子说明了 LSP(由鲍勃叔叔在我最近听到的播客中给出)是有时在自然语言中听起来正确的东西在代码.
A great example illustrating LSP (given by Uncle Bob in a podcast I heard recently) was how sometimes something that sounds right in natural language doesn't quite work in code.
在数学中,Square
是 Rectangle
.实际上,它是矩形的特化.is a"使您想通过继承对其进行建模.但是,如果在代码中您使 Square
从 Rectangle
派生,那么 Square
应该可以在您期望 Rectangle
的任何地方使用.这导致了一些奇怪的行为.
In mathematics, a Square
is a Rectangle
. Indeed it is a specialization of a rectangle. The "is a" makes you want to model this with inheritance. However if in code you made Square
derive from Rectangle
, then a Square
should be usable anywhere you expect a Rectangle
. This makes for some strange behavior.
想象一下,你的 Rectangle
基类上有 SetWidth
和 SetHeight
方法;这似乎完全合乎逻辑.但是,如果您的 Rectangle
引用指向 Square
,则 SetWidth
和 SetHeight
没有意义,因为设置一个会改变另一个以匹配它.在这种情况下,Square
没有通过 Rectangle
的 Liskov 替换测试,并且 Square
从 Rectangle
继承的抽象是一个坏的.
Imagine you had SetWidth
and SetHeight
methods on your Rectangle
base class; this seems perfectly logical. However if your Rectangle
reference pointed to a Square
, then SetWidth
and SetHeight
doesn't make sense because setting one would change the other to match it. In this case Square
fails the Liskov Substitution Test with Rectangle
and the abstraction of having Square
inherit from Rectangle
is a bad one.
你们都应该看看其他无价的SOLID 原则励志海报.
Y'all should check out the other priceless SOLID Principles Motivational Posters.
这篇关于什么是 Liskov 替换原则的例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!