之前以为接口回调可以起到js中ajax的作用,了解以后发现接口回调的含义在于接口。
1、先提供一个接口
public interface Callback {
void call();
}
2、再提供一个任务
public class Task {
public void executeWith(Callback callback) {
System.out.println("我已经做完工作了");
if (callback != null) {
callback.call();
}
}
}
3、不同的人做完任务以后的休息方式不同
public class Student implements Callback {
@Override
public void call() {
System.out.println("我要好好睡一觉");
}
}
public class Teacther implements Callback {
@Override
public void call() {
System.out.println("我要好好吃一顿");
}
}
4、测试一下
public class Test {
public static void main(String[] args) {
Task task = new Task();
task.executeWith(new Student());
task.executeWith(new Teacther());
}
}
5、输出如下
我已经做完工作了
我要好好睡一觉
我已经做完工作了
我要好好吃一顿
6、我的理解
这里的接口回调并没有起到想象中异步执行的作用,实际上我们把一个Callback接口做为excuteWith的参数传进去,然后在具体的实现中传入Callback的实现类,只体现了接口的多态性。对于接口回调这种设计模式欢迎讨论。