喜欢构成而不是继承? [英] Prefer composition over inheritance?

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

问题描述

为什么选择组合优于继承?每种方法都有哪些权衡取舍?什么时候应该选择继承而不是合成?

Why prefer composition over inheritance? What trade-offs are there for each approach? When should you choose inheritance over composition?

推荐答案

优先选择继承,因为它更具延展性/以后更容易修改,但不要使用compose-always方法。使用组合,可以使用依赖注入/设置器轻松更改行为。继承更加严格,因为大多数语言都不允许您从多个类型派生。因此,一旦你从TypeA派生,鹅就会或多或少地煮熟。

Prefer composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach. With composition, it's easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type. So the goose is more or less cooked once you derive from TypeA.

我对上述酸的测试是:


  • TypeB是否希望公开TypeA的完整接口(所有公共方法都不少),以便在需要TypeA的地方使用TypeB?表示继承

  • Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates Inheritance.

例如。如果不是更多,塞斯纳双翼飞机将暴露飞机的完整界面。因此,它适合从飞机派生。

e.g. A Cessna biplane will expose the complete interface of an airplane, if not more. So that makes it fit to derive from Airplane.


  • TypeB是否只想要TypeA公开的部分/部分行为?表示需要组合。

  • Does TypeB want only some/part of the behavior exposed by TypeA? Indicates need for Composition.

例如。鸟可能只需要飞机的飞行行为。在这种情况下,将其作为接口/类/两者提取出来并使其成为两个类的成员是有意义的。

e.g. A Bird may need only the fly behavior of an Airplane. In this case, it makes sense to extract it out as an interface / class / both and make it a member of both classes.

更新:刚回到我的回答,现在看来,如果没有特别提及Barbara Liskov的 Liskov替代原则作为'我是否应该继承此类型?'的测试?

Update: Just came back to my answer and it seems now that it is incomplete without a specific mention of Barbara Liskov's Liskov Substitution Principle as a test for 'Should I be inheriting from this type?'

这篇关于喜欢构成而不是继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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