喜欢组合而不是继承 [英] Favor composition over inheritance

查看:33
本文介绍了喜欢组合而不是继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

优先组合而不是继承

是非常流行的短语.我读了几篇文章,最后每篇文章都说

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.

这篇文章中的一个例子:

这里AppleFruit 之间有明显的IS-A 关系,即Apple IS-A Fruit,但作者也将其表示为Apple HAS-A Fruit (组合)以显示使用继承实现时的陷阱.

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 类是继承使用不当的一个很好的例子.它不是使用 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屋!

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