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 . (表示继承 。)
Does TypeB want only some/part of the behavior exposed by TypeA?
(TypeB是否只希望TypeA公开某些/部分行为?)
Indicates need for Composition. (表示需要组成。)
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替代原则 ,这是不完整的,以检验“我是否应该继承这种类型?”)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…