更喜欢组合而不是继承? [英] Prefer composition over inheritance?

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

问题描述

为什么更喜欢组合而不是继承?每种方法有什么权衡?什么时候应该选择继承而不是组合?

解决方案

更喜欢组合而不是继承,因为它更具延展性/易于以后修改,但不要使用始终组合的方法.组合,使用依赖注入/设置器可以很容易地动态改变行为.继承更加严格,因为大多数语言不允许您从多个类型派生.所以一旦你从 TypeA 派生出来,鹅就或多或少地煮熟了.

我对上述的酸性测试是:

  • TypeB 是否想要公开 TypeA 的完整接口(所有公共方法不少于),以便 TypeB 可以用于需要 TypeA 的地方?表示继承.

    • 例如塞斯纳双翼飞机将暴露飞机的完整界面,如果不是更多的话.所以这使它适合从 Airplane 派生.
  • TypeB 是否只想要 TypeA 公开的部分/部分行为?表示需要组合.

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

更新:刚刚回到我的答案,现在看来,如果没有具体提到 Barbara Liskov 的 Liskov Substitution Principle 作为我应该从这种类型继承吗?"的测试

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

解决方案

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.

My acid test for the above is:

  • 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.
  • 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.

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天全站免登陆