How to represent Callback in UML Class Diagram

2019-04-05 01:57发布

I have an Interface say

Interface ICallback {
    public void informFunction();
}

I have a Class say:

Class Implementation implements ICallback {

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

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

}

Now consider a class where in the instance of Class Implementation is passed as a interface and is used to make a callback.

Class AnotherImplementation {
   public ICallback mCallback;

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

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

Now I want to know how I can design a UML Class Diagram. Most importantly I need to know how to represent Callback Functionality that will happen in the Class AnotherImplementation :: testFunction().

1条回答
ゆ 、 Hurt°
2楼-- · 2019-04-05 02:42

Your code is represented in the following class diagram:

enter image description here

It represents the relationships between the classes:

  • Implementation implements ICallback
  • Implementation depends on AnotherImplementation (it creates one in its constructor)
  • AnotherImplementation has a ICallback (named mCallback)

A class diagram does not represent method functionality. Method functionality is visualized with a sequence or a Collaboration diagram.

In your example, the sequence diagram for testFucntion() is very simple:

sequence diagram

Note that the Implementation class does not show in the sequence diagram. This happens because the mCallback member is declared as ICallback. It could be anything that implements the ICallback interface.

I think that the more interesting question is how to visualize the method that triggers the callback. You don't mention which method of Implementation calls the testFunction() of AnotherImplementation, so I guess that this happens inside the constructor of Implementation. I created the following sequence diagram for this constructor:

callback sequence

Here you can see:

  1. Implementation creates the AnotherImplementation
  2. Implementation invokes testFunction on AnotherImplementation
  3. AnotherImplementation invokes informFunction on Implementation
查看更多
登录 后发表回答