java中回调方法的思想有些类似于模版方法设计模式,他们都将调用端需要的业务逻辑推迟到回调或者调用时才实现
下面用例子展示回调方法的template
/**
* 该类可以被调用客户端继承,也可以被实例化直接使用
* @author thinktown
*
*/
public class Template {
public interface CallbackInterface {
public void indo();
}
public void finalMethod(CallbackInterface callback) {
System.out.println("其实,我想用的是这个方法,但是里面的部分逻辑是可变化的,需要调用端自己实现");
callback.indo();
}
}
客户端1:
/**
* 继承template的调用客户端
*
* @author thinktown
*
*/
public class Client extends Template {
public void helloMethod() {
finalMethod(new CallbackInterface() {
@Override
public void indo() {
System.out.println("这才是真正需要执行的逻辑");
}
});
}
public static void main(String[] args) {
Client client = new Client();
client.helloMethod();
}
}
客户端2:
import org.sim.callback.test.Template.CallbackInterface;
/**
* 实现回调接口,实例化template实现回调
*
* @author thinktown
*
*/
public class Client2 implements CallbackInterface {
public void helloMethod() {
Template temp = new Template();
temp.finalMethod(new Client2());
}
public static void main(String[] args) {
Client2 client = new Client2();
client.helloMethod();
}
@Override
public void indo() {
System.out.println("这才是真正需要执行的逻辑");
}
}
执行结果都一样,在条件允许的情况下我认为用继承的方式更方便一点。