聚合与组合 [英] Aggregation versus Composition

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

问题描述

我很难理解 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.

我问这个问题的部分原因是因为我们在工作中进行了反向文档活动.我们已经编写了代码,但是我们需要返回并为代码创建类图.我们只想正确捕获关联.

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天全站免登陆