回調機制是什么哪?先上一幅圖來說明一下吧,這里用老師問問題,學生回答問題為例子,解釋一下回調機制的使用
首先需要一個接口callback,以及一個繼承了接口的類Teacher。Teahcer類中有另一個類Student的對象,在Teacher中執行函數,會調用student中的方法,student執行對應方法后再回調Teacher中重寫的接口方法,這樣就完成了一次回調方法。
1. 首先定義一個回調的接口
package callBackTest; public interface Callback { public void tellAnswer(int answer); }
2. 接下來定義老師的類,實現這個接口(老師類內部需要包含一個學生的對象)
package callBackTest; public class Teacher implements Callback { private Student student; public Teacher(Student student){ this.student = student; } public void askQuestion(final String question){ System.out.println("Teacher ask a question: "+ question); //提出一個問題 student.resolveQuestion(this,question); //詢問學生 System.out.println("Teacher: do someting else"); //忙自己的事 } @Override //重寫回調函數 public void tellAnswer(int answer){ System.out.println("your answer is: " + answer); } }
3. 最后定義學生的類
package callBackTest; public class Student { public void resolveQuestion(Callback callback, final String question){ System.out.println("Student receive the question: " + question); //學生收到老師的問題 System.out.println("Student: I am busy"); doSomething(); //學生在忙其他的事 callback.tellAnswer(2); //忙完之后回答問題 } public void doSomething(){ try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
4. 最后我們來測試一下回調機制
package callBackTest; public class Test { public static void main(String[] args){ Student st = new Student(); Teacher th = new Teacher(st); th.askQuestion("1+1=?"); } }
我們看看運行后的結果
Teacher ask a question: 1+1=? Student receive the question: 1+1=? Student: I am busy your answer is: 2 Teacher: do someting else
從運行結果可以看出,這里的回調機制其實是同步的,也就是說老師問過問題之后,會阻塞在那里,等待學生回答問題,然后才會去做自己的事情。
但實際中,老師問完問題,並不會等待學生回答,而是繼續做其他的事情,也就是異步回調。
實現異步回調,我們只需要修改Teacher這個類就可以了,將調用學生回答問題的操作封裝在一個線程中就可以了,也就是黃色部分。
package callBackTest; public class Teacher implements Callback { private Student student; public Teacher(Student student){ this.student = student; } public void askQuestion(final String question){ System.out.println("Teacher ask a question: "+ question); new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub student.resolveQuestion(Teacher.this,question); //這里需要注意必須聲明是Teacher.this } }).start(); System.out.println("Teacher: do someting else"); } @Override public void tellAnswer(int answer){ System.out.println("your answer is: " + answer); } }
我們再來看看運行后的結果,這里可以看出老師問過問題后就去忙自己的事情了,等學生回答完問題之后,就回調了自己的函數tellAnswer
Teacher ask a question: 1+1=? Teacher: do someting else Student receive the question: 1+1=? Student: I am busy your answer is: 2
Android中也使用了很多的回調機制,最常見的一個就是onClickListener,還有handle等,其實都是一個個的回調機制