I have some misunderstanding about terms of delegates and callbacks in Java.
class MyDriver {
public static void main(String[] argv){
MyObject myOb
This is a callback. According to Wikipedia:
In computer programming, a callback is a reference to a piece of executable code that is passed as an argument to other code.
So let's look at the executable code:
public void getHelp(HelpCallback callback){
//do something
callback.call(OK);
}
Here, the callback
argument is a reference to an object of type HelpCallback
. Since that reference is passed in as an argument, it is a callback.
Delegation is done internally by the object - independent of how the method is invoked. If, for example, the callback
variable wasn't an argument, but rather an instance variable:
class MyDriver {
public static void main(String[] argv){
// definition of HelpStrategy omitted for brevity
MyObject myObj = new MyObject(new HelpStrategy() {
@Override
public void getHelp() {
System.out.println("Getting help!");
}
});
myObj.getHelp();
}
}
class MyObject {
private final HelpStrategy helpStrategy;
public MyObject(HelpStrategy helpStrategy) {
this.helpStrategy = helpStrategy;
}
public void getHelp(){
helpStrategy.getHelp();
}
}
... then it would be delegation.
Here, MyObject
uses 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()
invokes helpStrategy.getHelp()
is not evident from the public interface of the MyObject
object or from the getHelp()
invocation. This kind of information hiding is somewhat characteristic of delegation.Also of note is the lack of a // do something
section in the getHelp()
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 something
section 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:
public void getHelp(HelpCallback callback){
helpStrategy.getHelp(); // perform logic / behavior; "do something" as some might say
if(callback != null) {
callback.call(); // invoke the callback, to notify the caller of something
}
}