组合、聚合和 DI
聚合:对象存在于其他对象之外,在外部创建,因此它作为参数(例如)传递给构造函数。例如:人-车。汽车是在不同的环境中创建的,然后成为个人财产。
组合:对象仅存在于另一个对象内部,或者仅在另一个对象内部才有意义,作为另一个对象的一部分。例如:人——心。你不会创造一颗心,然后将它传递给一个人。
这是否意味着对于 DI 框架,聚合是首选且更常见的方法,并且提高了可测试性?
这是否也意味着像 C# 这样的语言中缺乏多重继承的问题可以通过使用聚合来缓解。我一直听到以“组合与继承”为框架的讨论。这是有原因的吗?
Aggregation: the object exists outside the other, is created outside, so it is passed as an argument (for example) to the construtor. Ex: People – car. The car is create in a different context and than becomes a person property.
Composition: the object only exists, or only makes sense inside the other, as a part of the other. Ex: People – heart. You don’t create a heart and then pass it to a person.
Does this mean with DI frameworks, aggregation is the preferred and more common approach, and improves testability?
Does this also mean the lack of multiple inheritance in a language like C# can be mitigated through the use of aggregation. I have always heard the discussion framed in terms of "composition versus inheritance". Is there a reason for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
委托提供了比继承更灵活的解决方案 - 有一篇很好的文章,名为为什么扩展是邪恶的,它详细解释了这一点 - 然而哪个版本(无论是聚合还是组合)是学术性的 - 您已经确定了差异,以及使用哪个版本什么时候取决于你想要实现的目标。不过,通常可以通过接口来缓解多重继承的不足。
Delegation provides for a more flexible solution than inheritance - there is a good article called why extends is evil that explains more about this - however which version (whether it be Aggregation or Composition) is academic - you have identified the differences, and which one to use when is down to what you are trying to achieve. Lack of multiple inheritance is usually mitigated through interfaces though.