2013-12-10 259 views
7

我有一个接口说如何表示回调在UML类图

Interface ICallback { 
    public void informFunction(); 
} 

我有一个类说:

Class Implementation implements ICallback { 

    public Implementation() { 
     new AnotherImplementation(this); 
    } 

    @override 
    public void informFunction() { 
     // do something 
    } 

} 

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

Class AnotherImplementation { 
    public ICallback mCallback; 

    public AnotherImplementation(ICallback callback) { 
     mCallback = callback; 
    } 

    public void testFunction() { 
    mCallback.informFunction(); // Callback 
    } 
} 

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

回答

16

您的代码在下面的类图所表示:

enter image description here

它代表了类之间的关系:

  • Implementation实现ICallback
  • Implementation取决于AnotherImplementation(它在其构造函数中创建一个)
  • AnotherImplementation具有ICallback(名为mCallback)

类图不表示方法的功能性。方法功能可通过序列或协作图进行可视化。

在你的榜样,为testFucntion()序列图是非常简单的:

sequence diagram

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

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

callback sequence

在这里你可以看到:

  1. Implementation创建AnotherImplementation
  2. ImplementationAnotherImplementation
  3. AnotherImplementation调用testFunctionImplementation调用informFunction