英文:
UML relationship of class and object it creates inside the creation of another object?
问题
例如,在Java中:
public class App {
public void method() {
Object1 o1 = new Object1(new Object2(parameters));
}
}
我知道App和Object1之间有一个组合关系。
但是App和Object2呢?它也是一个组合关系吗?
英文:
For example, in java:
public class App {
public void method() {
Object1 o1 = new Object1(new Object2(parameters));
}
}
I know App and Object1 have a composition relationship.
But what about App and Object2? Is it a composition as well?
答案1
得分: 2
在方法中使用类不足以形成关联
你的类 App
没有包含类 Object1
或 Object2
的字段。它只是在方法的实现中使用了 Object1
和 Object2
。这对于建立关联是不足够的:App
和 ObjectX
之间没有概念上的关系,这只是实现的细节。由于组合是一种特殊类型的关联,所以这里也没有组合关系。
使用类意味着依赖关系
由于你的 App
使用了 Object1
和 Object2
,存在一个 «use»
依赖关系:App
需要了解这些类。你可以用一个带有开放箭头的虚线箭头表示这种依赖关系。
然而,你的示例中的依赖仅限于方法实现的级别,而不涉及类本身的级别。你可以用其他方式实现该方法。因此,我建议在你的模型中不要显示这种易变的依赖关系。只有在类定义本身会使用这样的对象时(例如,如果一个方法会返回一个 ObjectX
或使用一个 ObjectX
参数),才建议显示这种依赖关系。
术语:并非所有的组合都是组合!
如前所述,这里没有组合关系。尽管如此,这个词是有歧义的:
英文:
Using a class in a method is not sufficient for an association
Your class App
has no fields of class Object1
or Object2
. It just uses Object1
and Object2
in the implementation of a method. This is not sufficient for making an association: there is no conceptual relationship between App
and ObjectX
; it's just an implementation detail. And since composition is a special kind of association, there is no composition either.
Using a class means a dependency
Since your App
uses Object1
and Object2
, there is a «use»
dependency: App
needs to know these classes. You could show this dependency with an open headed dashed arrow.
However, the dependency in your example is only at the level of the method implementation and not at the level of the class itself. You could implement the method otherwise. I'd therefore advise not to show such a volatile dependency in your model. The dependency would be advisable if the class definition itself would use such an object (e.g. if a method would return an ObjectX
or use an ObjectX
parameter).
Terminology: Not all compositions are compositions!
As explained, there is no composition here. Nevertheless, the word is ambiguous:
-
it could mean object compostion. This is just about objects having fields of another class.
-
it could mean UML composition. This is a special kind of association with exclusive ownership
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论