How to represent Callback in UML Class Diagram

2019-04-05 02:53发布

问题:

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:

Your code is represented in the following class diagram:

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:

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:

Here you can see:

  1. Implementation creates the AnotherImplementation
  2. Implementation invokes testFunction on AnotherImplementation
  3. AnotherImplementation invokes informFunction on Implementation