有利于构成遗产 [英] Favor composition over inheritance
问题描述
喜欢组合继承
Favor composition over inheritance
是非常受欢迎的短语。我读了几篇文章,最后每篇文章都说:
is very popular phrase. I read several articles and at the end each article says
在类之间存在纯IS-A关系时使用继承。
use inheritance when there is pure IS-A relationship between classes.
这篇文章的一个例子:
在 Apple 和水果之间有明确的IS-A关系,即苹果IS-A水果,作者还将其显示为苹果HAS-A水果(构图),以便在继承时展现出陷阱。
Here between Apple and Fruit there is clear IS-A relationship i.e Apple IS-A Fruit, yet the author has also shown it as Apple HAS-A Fruit (composition) to show the pitfall when implemented with inheritance.
我在这里感到有些困惑,语句
I became somewhat confused here that what is the meaning of statement
在类之间存在纯IS-A关系时使用继承。
use inheritance when there is pure IS-A relationship between classes.
使用组合继承意味着始终尝试应用组合即使存在纯粹的IS-A关系,并保留继承只为那些
Does using composition over inheritance mean that always try to apply composition even if there is a pure IS-A relationship and leave inheritance only for those cases where composition does not make sense?
推荐答案
当您使用继承来重用超类中的代码时,而不是要覆盖方法并定义另一个多态性行为,通常表明您应该使用组合而不是继承。
When you use inheritance to reuse code from the superclass, rather than to override methods and define another polymorphic behavior, it's often an indication that you should use composition instead of inheritance.
java.util.Properties
class是一个坏的继承使用的例子。而不是使用Hashtable来存储其属性,而是扩展 Hashtable,以便重用其方法,并避免使用委托重新实现其中的一些。
The java.util.Properties
class is a good example of a bad use of inheritance. Rather than using a Hashtable to store its properties, it extends Hashtable, in order to reuse its methods and to avoid reimplementing some of them using delegation.
这篇关于有利于构成遗产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!