组合、聚合和 DI

发布于 2024-09-01 20:08:44 字数 317 浏览 2 评论 0原文

聚合:对象存在于其他对象之外,在外部创建,因此它作为参数(例如)传递给构造函数。例如:人-车。汽车是在不同的环境中创建的,然后成为个人财产。

组合:对象仅存在于另一个对象内部,或者仅在另一个对象内部才有意义,作为另一个对象的一部分。例如:人——心。你不会创造一颗心,然后将它传递给一个人。

这是否意味着对于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

童话里做英雄 2024-09-08 20:08:44

委托提供了比继承更灵活的解决方案 - 有一篇很好的文章,名为为什么扩展是邪恶的,它详细解释了这一点 - 然而哪个版本(无论是聚合还是组合)是学术性的 - 您已经确定了差异,以及使用哪个版本什么时候取决于你想要实现的目标。不过,通常可以通过接口来缓解多重继承的不足。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文