英文:
Why if one class forms a composition with another class, a different class can be asocciated with the composed class?
问题
名为Fruits的类与名为Apple的类形成组合关系。这意味着只有在实例化某个水果对象时,苹果才会被实例化。现在我的问题是,如果只有在实例化水果时苹果才会被实例化,那么当苹果对象在水果内部时,第三个类"Tasty Fruits"怎么可能通过关联关系访问苹果对象呢?
如果苹果对象在水果内部,那么这种关联关系不就违反了组合关系吗?我的意思是,为了访问苹果,美味水果需要访问水果,因为苹果在水果内部。我不明白这个UML图是如何合理的,也不明白为什么可以这样设计。
英文:
Look at the following example:
The class named Fruits forms a composition with the class named Apple. That means that apples will be only instantiated when some fruit object is instantiated. Now my question is, if apples are only instantiated when fruits are instantiated how is it possible that a third class "Tasty Fruits" can access apple objects with an association relation if apple objects are inside fruits?
Wouldn't that association relation contradict the composition? I mean, in order to access apples, tasty fruits would need to access fruits as apples are inside fruits. I don't understand how and why this UML diagram is fine.
答案1
得分: 4
复合聚合意味着Fruit
组合的Apples
组件的生命周期由拥有它们的Fruit
管理。这不妨碍Apples
直接与其他类相关联。如果果实一侧的多重性是0..1
,那么Apples
甚至可以存在而不被Fruit
所拥有。
话虽如此,对于类似A、B、C的类来说,图表是可以的。但是,用所选的类来说,这非常令人困惑:在现实生活中,一个Apple
是一种Fruit
,而一个Fruit
实例(例如一个给定的草莓)并不由一个或多个苹果组成。类似地,Tasty Fruit
也是一种Fruit
,与Apple
的关联就像组合一样奇怪。
换句话说,问题不在于UML规则,而在于通常与所选类相关联的语义。
英文:
The composite aggregation means that Apples
components of a Fruit
composite have their lifecycle managed by the Fruit
that owns them.
This does not prevent Apples
to be associated directly with other classes. Apples
could even exist without being owned by Fruit
if the multiplicity on the fruit side would be 0..1
.
That being said, the diagram would be ok, with classes such as A, B, C. But it is very confusing, with the classes chosen : in real life an Apple
is a Fruit
, and a Fruit
instance (e.g. a given strawberry) is not composed of one or more apples. Similarly, a Tasty Fruit
is also a Fruit
and the association with Apple
is as weird as a the composition.
In other words, the issue is not the UML rules, but the semantics usually associated with the chosen classes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论