如果一个类与另一个类形成组合,不同的类可以与组合后的类相关联吗?

huangapple go评论68阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月27日 05:51:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575227.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定