gpt4 book ai didi

design-patterns - 设计模式是组合还是继承?

转载 作者:行者123 更新时间:2023-12-04 07:16:11 24 4
gpt4 key购买 nike

大多数人更喜欢组合而不是继承,

但是这样做的显着好处是什么?

最佳答案

这篇文章应该会给你一个完整的答案: Design Principles from Design Patterns: Composition versus inheritance

我在这里引用 Erich Gamma 的直接回答:

I still think it's true even after ten years. Inheritance is a cool way to change behavior. But we know that it's brittle, because the subclass can easily make assumptions about the context in which a method it overrides is getting called. There's a tight coupling between the base class and the subclass, because of the implicit context in which the subclass code I plug in will be called. Composition has a nicer property. The coupling is reduced by just having some smaller things you plug into something bigger, and the bigger object just calls the smaller object back. From an API point of view defining that a method can be overridden is a stronger commitment than defining that a method can be called.

In a subclass you can make assumptions about the internal state of the superclass when the method you override is getting called. When you just plug in some behavior, then it's simpler. That's why you should favor composition. A common misunderstanding is that composition doesn't use inheritance at all. Composition is using inheritance, but typically you just implement a small interface and you do not inherit from a big class. The Java listener idiom is a good example for composition. With listeners you implement a listener interface or inherit from what is called an adapter. You create a listener object and register it with a Button widget, for example. There is no need to subclass Button to react to events.

关于design-patterns - 设计模式是组合还是继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2424643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com