@Yano
2017-08-06T17:32:01.000000Z
字数 1039
阅读 1755
Java
public interface Callback {
public void tellAnswer(int answer);
}
public class Teacher implements Callback {
private Student student;
public Teacher(Student student) {
this.student = student;
}
public void askQuestion() {
student.resolveQuestion(this);
}
@Override
public void tellAnswer(int answer) {
System.out.println("知道了,你的答案是" + answer);
}
}
public interface Student {
public void resolveQuestion(Callback callback);
}
public class Ricky implements Student {
@Override
public voidresolveQuestion(Callback callback) {
// 模拟解决问题
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
// 回调,告诉老师作业写了多久
callback.tellAnswer(3);
}
}
@Test
public void testCallBack() {
Student student = new Ricky();
Teacher teacher = new Teacher(student);
teacher.askQuestion();
}
Student也可以使用匿名类定义,更加简洁:
@Test
public void testCallBack2() {
Teacher teacher = new Teacher(new Student() {
@Override
public void resolveQuestion(Callback callback) {
callback.tellAnswer(3);
}
});
teacher.askQuestion();
}
Teacher 中,有一个解决问题的对象:Student,在Student中解决问题之后,再通过引用调用Teacher中的tellAnswer接口,所以叫回调
。