如何在UML类图中表示回调

我有一个界面说

Interface ICallback { public void informFunction(); } 

我有一个class级说:

 Class Implementation implements ICallback { public Implementation() { new AnotherImplementation(this); } @override public void informFunction() { // do something } } 

现在考虑一个类,其中Class Implementation的实例作为接口传递并用于进行回调。

 Class AnotherImplementation { public ICallback mCallback; public AnotherImplementation(ICallback callback) { mCallback = callback; } public void testFunction() { mCallback.informFunction(); // Callback } } 

现在我想知道如何设计UML类图。 最重要的是,我需要知道如何表示将在类AnotherImplementation :: testFunction()中发生的回调函数。

您的代码在以下类图中表示:

在此处输入图像描述

它代表了类之间的关系:

  • Implementation实现了ICallback
  • Implementation依赖于AnotherImplementation (它在构造函数中创建一个)
  • AnotherImplementation有一个ICallback (名为mCallback)

类图不代表方法function。 使用序列或协作图可视化方法function。

在您的示例中, testFucntion()的序列图非常简单:

序列图

请注意, Implementation类不会显示在序列图中。 发生这种情况是因为mCallback成员被声明为ICallback 。 它可以是任何实现ICallback接口的东西。

我认为更有趣的问题是如何可视化触发回调的方法。 你没有提到Implementation哪个方法调用AnotherImplementationtestFunction() ,所以我猜这发生在Implementation的构造函数中。 我为这个构造函数创建了以下序列图:

回调序列

在这里你可以看到:

  1. Implementation创建了AnotherImplementation
  2. ImplementationAnotherImplementation上调用testFunction
  3. informFunctionImplementation上调用informFunction