问题
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
implementsICallback
Implementation
depends onAnotherImplementation
(it creates one in its constructor)AnotherImplementation
has aICallback
(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:
Implementation
creates theAnotherImplementation
Implementation
invokestestFunction
onAnotherImplementation
AnotherImplementation
invokesinformFunction
onImplementation
来源:https://stackoverflow.com/questions/20491501/how-to-represent-callback-in-uml-class-diagram