聚合与组合 [英] Aggregation versus Composition

查看:148
本文介绍了聚合与组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解UML中的组合和聚合之间的区别。有人能给我一个很好的比较和对比吗?我也很乐意学习识别代码之间的差异和/或看到一个简短的软件/代码示例。



编辑:为什么我的一部分原因问是因为我们正在做的反向文档活动。我们编写了代码,但是我们需要返回并为代码创建类图。我们只想正确地捕获关联。

解决方案

聚合和组合之间的区别取决于上下文。

在另一个答案中提到的汽车示例 - 是的,汽车尾气可以独自站立,所以可能不会与汽车组合 - 但这取决于应用程序。如果您构建一个实际上必须处理独立汽车排气(汽车店管理应用程序?)的应用程序,则聚合将成为您的选择。但是,如果这是一个简单的赛车游戏,而且汽车尾气只能作为汽车的一部分,那么组合就会很好。



棋盘?同样的问题。只有在某些应用中,棋盘才可以不用棋盘。在其他玩具制造商(如玩具制造商)中,棋子肯定不会组成棋盘。



尝试映射构图/聚合时,事情变得更糟到你最喜欢的编程语言。在一些语言中,差异可以更容易地注意到(通过引用与按价值,当事情很简单),但在其他语言中可能不存在。



<最后一个建议?不要浪费太多时间在这个问题上。这不值得。这个区别在实践中几乎没有用(即使你有一个完全清晰的组合,你可能仍然希望通过技术原因将其实现为一个聚合 - 例如缓存)。


I've had a hard time understanding the difference between composition and aggregation in UML. Can someone please offer me a good compare and contrast between them? I'd also love to learn to recognize the difference between them in code and/or to see a short software/code example.

Edit: Part of the reason why I ask is because of a reverse documentation activity that we're doing at work. We have written the code, but we need to go back and create class diagrams for the code. We'd just like to capture the associations properly.

解决方案

The distinction between aggregation and composition depends on context.

Take the car example mentioned in another answer - yes, it is true that a car exhaust can stand "on its own" so may not be in composition with a car - but it depends on the application. If you build an application that actually has to deal with stand alone car exhausts (a car shop management application?), aggregation would be your choice. But if this is a simple racing game and the car exhaust only serves as part of a car - well, composition would be quite fine.

Chess board? Same problem. A chess piece doesn't exist without a chess board only in certain applications. In others (like that of a toy manufacturer), a chess piece can surely not be composed into a chess board.

Things get even worse when trying to map composition/aggregation to your favorite programming language. In some languages, the difference can be easier to notice ("by reference" vs. "by value", when things are simple) but in others may not exist at all.

And one last word of advice? Don't waste too much time on this issue. It isn't worth it. The distinction is hardly useful in practice (even if you have a completely clear "composition", you may still want to implement it as an aggregation due to technical reasons - for example, caching).

这篇关于聚合与组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆