如何在 UML class 图中用泛型表示依赖注入?

How to represent dependency injection with generics in UML class diagram?

我无法在 UML class 图中表示以下代码段:

public class Test {
    // something
}

public class Bar<T> {
    private T item;

    public Bar(T item) {
        this.item = item;
    }

    // something
}

public class Foo<T> {
    private Bar<T> bar;

    public Foo(Bar<T> bar) {
        this.bar = bar;
    }

    // something
}

public class Caller {
    private Test item;
    private Foo<Test> foo;
    private Bar<Test> bar;

    public Caller() {
        item = new Test();
        bar = new Bar<Test>(item);
        foo = new Foo<Test>(bar);
    }

    // something
}

到目前为止,我想这样表示:

因为我知道你不能直接绑定一个关联,但你首先需要一个绑定 class。我不知道它是否正确,如果正确,当有更多 classes 时,这不会导致更复杂的图表吗?

完成你的图表?

无法绑定关联的假设似乎没有根据。根据 UML 规范,classifier 可以被模板化,并且可以绑定模板。这对于 classes 来说很简单。关联也是 class 赋值者,我没有发现一般规则不适用于它们的证据。

因此,如果您认为它可以提高可读性,您可以很好地完成图表。使用相同的符号:在 Foo_TestBar_Test 之间添加一个关联,以及从该关联到模板关联的 «bind» 箭头(顺便说一句。link 带有两行箭头,但即使它是速率,它也是合法的;泛化也可以用于关联,参见 )。

如何在 UML 中使用模板

模板是一个额外的抽象层次。保持在同一抽象级别的模型往往更容易理解。因此,最好在专注于“元”级别的单独图表中隔离模板 classes(图表底部)之间的关系。

那么显示一组绑定 class 并使用模板突出显示其中一个绑定就不是问题了 class: reader 可以很容易地参考其他图表。但是,当与绑定结合使用时,teplates 很快就会产生非常复杂且难以理解的图表。

您可能更喜欢让图表尽可能简单。

但首先,让我们澄清一下模板和绑定 class 之间的 «bind» 关系。既不是继承也不是实现,还有一些未解之谜:

A Classifier that is parameterized using a RedefinableTemplateSignature is called a template Classifier, while a Classifier with one or more TemplateBindings is called a bound Classifier.

(...) the details of how the contents are merged into a bound element are left open. In the case of Classifier the semantics are equivalent to inserting an anonymous general bound Classifier representing the intermediate result for each binding, and specializing all these intermediate results by the bound Classifier.

(...) A bound Classifier may have contents in addition to those resulting from its bindings.

因此,UML 并未完全定义模板的工作方式,但您可以假设绑定 class 从模板。

简化图表?

考虑到这一点,您可以使用符号快捷方式:该符号允许您显示匿名绑定 class,直接使用 class 中的绑定。然后绑定箭头是隐含的。此外,对 Test 的依赖也变得隐式,简化了图表。

理想情况下,底部部分应在单独的图表中。但是如果你保留它,你可能会避免 BarTest 之间的关联(因为它是从模板中的 item: T 推导出来的),除非你认为它很重要。