I have some misunderstanding about terms of delegates and callbacks in Java.
class MyDriver {
public static void main(String[] argv){
MyObject myObj = new MyObject();
// definition of HelpCallback omitted for brevity
myObj.getHelp(new HelpCallback () {
@Override
public void call(int result) {
System.out.println("Help Callback: "+result);
}
});
}
}
class MyObject {
public void getHelp(HelpCallback callback){
//do something
callback.call(OK);
}
}
Is it callback or delegate (Are delegates and callbacks the same or similar?)?
How to implement then another one?
This is a callback. According to Wikipedia:
So let’s look at the executable code:
Here, the
callbackargument is a reference to an object of typeHelpCallback. Since that reference is passed in as an argument, it is a callback.An example of delegation
Delegation is done internally by the object – independent of how the method is invoked. If, for example, the
callbackvariable wasn’t an argument, but rather an instance variable:… then it would be delegation.
Here,
MyObjectuses the strategy pattern. There are two things to note:getHelp()doesn’t involve passing a reference to executable code. i.e. this is not a callback.MyObject.getHelp()invokeshelpStrategy.getHelp()is not evident from the public interface of theMyObjectobject or from thegetHelp()invocation. This kind of information hiding is somewhat characteristic of delegation.Also of note is the lack of a
// do somethingsection in thegetHelp()method. When using a callback, the callback does not do anything relevant to the object’s behavior: it just notifies the caller in some way, which is why a// do somethingsection was necessary. However, when using delegation the actual behavior of the method depends on the delegate – so really we could end up needing both since they serve distinct purposes: