Java回调函数
所谓回调,就是客户程序C调用服务程序S中的某个函数A,然后S又在某个时候反过来调用C中的某个函数B,对于C来说,这个B便叫做回调函数。举个例子:学生Student向老师Teacher提问,然后Teacher再回答学生的问题。此问题涉及两个类Student和Teacher。
- 首先在Teacher类中定义askQuestion方法,学生通过此方法向老师提问。
- 老师在收到问题后,经过思索后,需要回答学生的问题,此刻老师需要知道通过什么方式把答案告诉给学生,保证答案能够准确的传递到发问的这个学生,此时就需要定义一个公共的接口,老师通过此接口把答案传递给学生。
Demo:
- 定义用于传递答案的接口:
1 package com.hxl.callback.service; 2 3 public interface Answer { 4 5 public void answerMe(String theAnswer); 6 }
- 定义学生类:学生类需要实现预先约定好的公共接口,以便接收老师传递的答案:
1 package com.hxl.callback.service; 2 3 public class Student implements Answer{ 4 5 public Teacher teahcer; 6 7 public void answerMe(String theAnswer) { 8 System.out.println(theAnswer); 9 } 10 11 12 }
- 定义老师类:老师收到学生提出的问题后,经过思索得出答案,通过预先定义好的接口将答案传递给提问的学生
1 package com.hxl.callback.service; 2 3 public class Teacher { 4 5 public Answer answer; 6 7 public void askQuestion(String theQuestion) { 8 System.out.println(theQuestion); 9 } 10 11 public void answerQuestion(String theAnswer) { 12 answer.answerMe(theAnswer); 13 } 14 }
- 测试:
1 package com.hxl.callback.test; 2 3 import org.junit.Test; 4 5 import com.hxl.callback.service.Teacher; 6 import com.hxl.callback.service.Student; 7 8 public class TestCallBack { 9 10 @Test 11 public void testCallBack() { 12 //实例化学生 13 Student student = new Student(); 14 //设定学生向谁发问 15 student.teahcer = new Teacher(); 16 //学生调用老师的askQuestion方法,向老师发问 17 student.teahcer.askQuestion("1+1=?"); 18 //老师注册约定的回调接口 19 student.teahcer.answer = student; 20 //老师回答学生的问题 21 student.teahcer.answerQuestion("1+1=2"); 22 } 23 24 }
TIPS:对于Student来说answerMe方法即为回调函数。