回调方法介绍
回调方法就是一个参数,将一个A方法作为参数传到B方法里面,当B方法执行完之后,再执行传进去的这个A方法,这个过程就叫做回调。
程序示例
下面用一个简单的Java类说明回调的作用:
首先比如你准备吃饭,但是要等到一段时间之后才吃饭,也就是吃饭这个动作由你执行,但是时间上还要等待,所以你想要叫你的妈妈来叫你去吃饭。我们定义一个eat方法,它的入参包含了Mymother这个对象和一个long类型的时间
public class Me {
public void eat(Mymother m , long time){
System.out.println("zim eat");
m.call(this,time);
}
public void callback(){
System.out.println("me call function");
}
}
因此在Mymother类中,应该有一个call的方法,用来会叫你去吃饭,因此Mymother类的定义如下:
public class Mymother {
//调用方法
public void call(Me me,long time){
int i=0;
while(i++==time) {
System.out.println("use my mother");
}
me.callback();
}
}
在测试类中我们分别初始化Me和Mymother类的对象,然后执行Me中的方法调用:
public class Test {
public static void main(String[] args) {
Me m=new Me();
Mymother mymother=new Mymother();
m.eat(mymother,1000);
}
}
代码的运行结果:
zim eat
use my mother
me call function
可以看到我们的调用过程,A-> B ->A的过程,从Me的方法中引用Mymother,最终回到Me对象的调用方法callback,完成这个过程。
回调的过程实现起来也十分简单,只需要让被回调的对象实现回调的方法。