对Android回调的理解

来源:互联网 发布:linux查看磁盘io负载 编辑:程序博客网 时间:2024/06/10 01:19

场景:

C问S一个问题,但S不能马上给他答案,于是S决定想到答案再告诉C。S约定通过打电话的方式告诉C,C需要留下电话给S。

S将答案告诉C是回调,联系方式是S和C先约定好的接口,C留联系方式给S是注册过程。


代码:

[java] view plain copy
 print?
  1. //声明一个接口 ,约定好工具  
  2. public interface Tool {    
  3.     void answer();    
  4. }    
  5.   
  6. public class C {    
  7.     private Tool tool;    
  8.     public void setCallBack(Tool tool) {    
  9.         this.tool = tool;    
  10.     }    
  11.     public void ask() {    
  12.         tool.answer();    
  13.     }    
  14. }    
  15.    
  16. public class S {    
  17.     public static void main(String[] args) {    
  18.         C c = new C();    
  19.         //c使用setCallBack()留联系方式,留的内容是Tool  
  20.         c.setCallBack(new Tool() {    
  21.             public void answer() {    
  22.                 System.out.println("answer the question.");    
  23.             }    
  24.         });    
  25.         c.ask();  
  26.     }    
  27. }