简体   繁体   English

组合vs inheritance,多态性呢?

[英]Composition vs inheritance, what about polymorphism?

There is a design principle stating that you should favor composition over inheritance but isn't it true that this doesn't hold when we want to make use of polymorphism?有一个设计原则表明你应该更喜欢组合而不是 inheritance,但是当我们想要使用多态性时,这不是真的吗?

For example if we want to do something for several related objects, we might want to iterate over a for-each-loop only stating that the object performing the method is-a some supertype , how would we get that functionality and code reuse using composition?例如,如果我们想为几个相关的对象做某事,我们可能想迭代一个 for-each-loop,只说明执行该方法的 object 是某个超类型,我们如何使用组合获得该功能和代码重用?

In statically typed languages where polymorphism is tied to inheritance, that inheritance can be achieved in two ways: one way is stateful and the other way is stateless.在多态性与 inheritance 相关联的静态类型语言中,inheritance 可以通过两种方式实现:一种方式是有状态的,另一种方式是无状态的。 These may be referred to as implementation inheritance versus specification inheritance , respectively.这些可以分别称为实现 inheritance规范 inheritance For example, in Java, class inheritance is stateful whereas interface inheritance is stateless.例如,在 Java、class inheritance 是有状态的,而接口 Z5FED3411FAF832174EF1F04C21 是无状态的。

With that in mind, when the Gang of Four book says,考虑到这一点,当四人帮的书说,

Favor object composition over class inheritance.在 class inheritance 上更喜欢 object 组合。

...they are referring to stateful inheritance. ...他们指的是有状态的 inheritance。 So polymorphism can still be achieved through stateless inheritance while following this principle, even in statically typed languages.所以多态性仍然可以通过无状态 inheritance 在遵循这一原则的情况下实现,即使在静态类型语言中也是如此。

(In dynamically typed languages there is no relationship between polymorphism and inheritance, because polymorphism does not require explicit type declarations.) (在动态类型语言中,多态性和 inheritance 之间没有关系,因为多态性不需要显式类型声明。)

What the Gang of Four were worried about was this.四人组担心的是这个。

...designers often overuse inheritance as a reuse technique, [but] designs are often made more reusable (and simpler) by depending more on object composition. ...设计师经常过度使用 inheritance 作为重用技术,[但] 设计通常通过更多地依赖于 object 组合而变得更可重用(和更简单)。

I often phrase this as, " inheritance is a poor tool for code reuse. " In other words, don't use inheritance to keep your code DRY .我经常这样说,“ inheritance 是一个糟糕的代码重用工具。 ”换句话说,不要使用 inheritance 来保持代码DRY Composition is better for that.作曲更好。 Stateless inheritance, on the other hand, is not intended for code reuse and is a great tool for polymorphism.另一方面,无状态 inheritance 不适合代码重用,是多态性的绝佳工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM