自我记录 自我记录
回调函数概念还是比较清晰的:
A调用B中的方法,B完成该方法之后,再调用A中的某方法
举个栗子,现在有老师跟学生,老师问学生一个问题,学生回答该问题,回答完之后通知老师问题的答案是多少!
根据上面的叙述,可以这么做:
首先声明一个接口,这个接口让老师来实现,接口的目的是,当学生回答问题之后,通知老师问题已回答完毕
package com.mine.callback;
public interface Callback {
void callback(String result);
}
接口完毕之后,让老师实现该接口
package com.mine.callback;
public class Teacher implements Callback {
Student student;
public Teacher(Student student) {
this.student = student;
}
@Override
public void callback(String result) {
System.out.println("老师得到的答案是:" + result);
}
public void askQuestion(int i, int j) {
System.out.println("老师的问题是:" + i + " + " + j + " = ?");
student.ansQuestion(i, j, this);
}
}
然后再实现学生类
package com.mine.callback;
public class Student {
public void ansQuestion(int i, int j, Callback callback) {
System.out.println("学生得到的问题是:" + i + " + " + j + " = ?");
try {//问题比较难,需要思考两秒钟
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int result = i + j;
System.out.println("学生想了两秒钟后回答!");
//回答完毕了,再通知老师(因为老师实现了Callback接口,因此可以这么调用)
callback.callback(result + "");
}
}
使用测试类:
package com.mine.callback;
public class Client {
public static void main(String[] args) {
Student student = new Student();
Teacher teacher = new Teacher(student);
teacher.askQuestion(2, 3);
}
}
最后运行得到的结果是: