A callback is a piece of code that you pass as an argument to some other code so that it executes it. Since Java doesn't yet support function pointers, they are implemented as Command objects. Something like
public class Test {
public static void main(String[] args) throws Exception {
new Test().doWork(new Callback() { // implementing class
@Override
public void call() {
System.out.println("callback called");
}
});
}
public void doWork(Callback callback) {
System.out.println("doing work");
callback.call();
}
public interface Callback {
void call();
}
}
A callback will usually hold reference to some state to actually be useful.
By making the callback implementation have all the dependencies to your code, you gain indirection between your code and the code that is executing the callback.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…