Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

language-agnostic - 比继承更偏爱组成?(Prefer composition over inheritance?)

Why prefer composition over inheritance?

(为什么更喜欢使用组合而不是继承?)

What trade-offs are there for each approach?

(每种方法都有哪些取舍?)

When should you choose inheritance over composition?

(什么时候应该选择继承而不是合成?)

  ask by Readonly translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(因此,一旦从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?

    (TypeB是否要公开TypeA的完整接口(所有公共方法不少于此),以便可以在需要TypeA的地方使用TypeB?)

    Indicates Inheritance .

    (表示继承 。)

    • eg A Cessna biplane will expose the complete interface of an airplane, if not more.

      (例如,塞斯纳(Cessna)双翼飞机将展示飞机的完整界面,甚至更多。)

      So that makes it fit to derive from Airplane.

      (因此,它很适合从飞机中派生。)

  • Does TypeB want only some/part of the behavior exposed by TypeA?

    (TypeB是否只希望TypeA公开某些/部分行为?)

    Indicates need for Composition.

    (表示需要组成。)

    • eg 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?'

(更新:刚刚回到我的答案,现在似乎没有完整提及Barbara Liskov的Liskov替代原则 ,这是不完整的,以检验“我是否应该继承这种类型?”)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...