[关闭]
@Yano 2017-08-06T09:32:01.000000Z 字数 1039 阅读 1043

Java 回调机制

Java


参考链接

Java回调机制解读

回调的思想

  1. 类A的a()方法调用类B的b()方法
  2. 类B的b()方法执行完毕主动调用类A的callback()方法

代码分析

  1. public interface Callback {
  2. public void tellAnswer(int answer);
  3. }
  4. public class Teacher implements Callback {
  5. private Student student;
  6. public Teacher(Student student) {
  7. this.student = student;
  8. }
  9. public void askQuestion() {
  10. student.resolveQuestion(this);
  11. }
  12. @Override
  13. public void tellAnswer(int answer) {
  14. System.out.println("知道了,你的答案是" + answer);
  15. }
  16. }
  17. public interface Student {
  18. public void resolveQuestion(Callback callback);
  19. }
  20. public class Ricky implements Student {
  21. @Override
  22. public voidresolveQuestion(Callback callback) {
  23. // 模拟解决问题
  24. try {
  25. Thread.sleep(3000);
  26. } catch (InterruptedException e) {
  27. }
  28. // 回调,告诉老师作业写了多久
  29. callback.tellAnswer(3);
  30. }
  31. }

测试

  1. @Test
  2. public void testCallBack() {
  3. Student student = new Ricky();
  4. Teacher teacher = new Teacher(student);
  5. teacher.askQuestion();
  6. }

Student也可以使用匿名类定义,更加简洁:

  1. @Test
  2. public void testCallBack2() {
  3. Teacher teacher = new Teacher(new Student() {
  4. @Override
  5. public void resolveQuestion(Callback callback) {
  6. callback.tellAnswer(3);
  7. }
  8. });
  9. teacher.askQuestion();
  10. }

分析

Teacher 中,有一个解决问题的对象:Student,在Student中解决问题之后,再通过引用调用Teacher中的tellAnswer接口,所以叫回调

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注