回调方法是什么及其理解

  回调方法是类A调用类B的方法,然后B又在某个时候反过来调用类B的方法a,这个a就是回调方法.

  上面这句话读起来绕口且还是对于回调方法还是没有什么实质性的理解,下面举个例子来解释回调方法:

  儿子(Son)要睡午觉了,告诉妈妈(Mother)要一个小时之后叫他醒来,下面是两个类的定义

 1 public class Son {
 2 
 3     public void sleep(Mother m,int time){
 4         System.out.println("son:sleep");
 5         m.call(this,time);//告诉妈妈多久叫醒自己
 6     }
 7     
 8     public void aware(){
 9         System.out.println("son:aware");
10     }
11 }
 1 public class Mother {
 2 
 3     //这里简单起见使用的是用i判断
 4     public void call(Son s,int time){
 5         int i=0;
 6         while(i++==time);
 7         System.out.println("mother:call");
 8         s.aware();//回调
 9     }
10     
11 }

  测试代码

1 public class Test {
2 
3     public static void main(String[] args) {
4         Son s=new Son();
5         Mother m=new Mother();
6         s.sleep(m,100);
7     }
8 }

  在儿子睡觉之前告诉妈妈经过time时间后叫醒自己(this),妈妈在到时间之后,叫醒儿子(s.aware()).这里儿子对应定义中的类A,妈妈对应定义中的类B,aware()方法就是回调方法.a

  以下是个人对回调方法的理解:

  回调使一个功能模块更加灵活,比如上述例子中是儿子让妈妈叫醒他,那么假如又多了一个爸爸也想让妈妈叫醒他呢,这里又需要重载一个call,这里可能会有人说,使用多态实现啊!那假如不是儿子叫妈妈叫醒他自己,而是叫妈妈"叫醒"电视机呢,这里的电视机跟儿子总不会有同一个父类吧.而使用了回调方法,你只需要让被叫醒的对象实现aware()方法即可,使功能模块能够更加灵活.

  在许多框架中都都能看到回调的影子,比如spring在IOC容器初始化时,父容器会调用子容器的方法,子容器也会调用父容器的方法.

原文地址:https://www.cnblogs.com/ouhaitao/p/8547907.html