We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(5)
我认为他的意思可能是继承可能被过度使用,即使在组合是更好的解决方案的情况下也是如此。这在多本书中都有讨论,例如
I think what he might have meant is that inheritance can be overused, even in cases where composition would be a better solution. This is discussed in several books, e.g.
并非每次都要避免,但无论何时,当您陷入超类中定义的一组操作时,它都会阻碍灵活性。基本的设计思想是“固定的部分留给继承,可变的部分注入”。
在Head First Design Patterns中有一个很好的例子。
假设您决定使用实现 Fly() 的基类来建模鸭子。假设你有一只橡皮鸭,它当然不会飞。您可以使用不执行任何操作的方法重写 Fly() 。但有一天,你添加了 DecoyDuck 并忘记重写 Fly(),结果就会变得一团糟。最好构建注入所需行为的 DecoyDuck(组合优于继承)。
Not to be avoided every time, but it hinders flexibility wherever you are stuck with a defined set of operations from a superclass. The basic design idea is "leave to inheritance the fixed parts and inject the parts subject to change".
In Head First Desing Patterns there is a good example.
Say you decide to model ducks with a base class which implements fly(). Say that you have a RubberDuck, who can't fly, of course. You override fly() with a method that does nothing. But then some day you add DecoyDuck and forget to override fly() and you get a mess. It would have been better to build the DecoyDuck injecting the desired behaviour (composition over inheritance).
C++ 中的良好编码实践更喜欢通过聚合进行组合。参见“C++ 编码标准:101 条规则、指南和最佳实践”作者:萨特/亚历山大雷斯库
Good coding practice in C++ prefers composition through aggregation. cf. "C++ Coding Standards: 101 Rules, Guidelines, And Best Practices" by Sutter/Alexandrescu
不应“按原样”避免继承。
当您想要定义/描述“是”关系时,应该使用(并且仅使用)继承。
当一个实体“不是”另一个实体时,该实体不应继承另一个实体。
在这种情况下,应使用组合。
Inheritance should not be avoided 'as is'.
Inheritance should be used (and only used) when you want to define / describe an 'is a' relationship.
When an entity 'is not' anotherentity, entity should not inherit from anotherentity.
In such cases, composition should be used.
继承有助于泛化(在 OOP 术语中是向上转型),而组合有助于行为定义(控制反转 - 或依赖注入)。
应该使用哪一个带来更多好处;但支持组合也使代码更具可扩展性。因此,代码变得“禁止修改,但开放扩展”,因此“HAS-A 比 IS-A 更好”。
有点像你自己是一辆车或拥有一辆车(或没有?)
Inheritance helps generalization (which is upcasting in OOP terms), whereas Composition helps behavior definition (Inversion of Control - or Dependency Injection).
One should use whichever grants more benefit; but favoring Composition also makes the code more extend-able. Thus, the code becomes "closed to modification, but open to extension" and thus "HAS-A is better than IS-A".
Kind of like being a car yourself or owning a car (or not?)