java 回调机制原理及示例

来源:互联网 发布:苹果签名软件 编辑:程序博客网 时间:2024/05/01 07:30
 

    今天讲的内容重点是回调机制,这是java里面动态绑定的又一面貌。
    动态绑定:我们用父类的引用指向子类的对象,Father father = new Son();,内存上,是一个叠加的原理。子类继承于父类,重写父类里面的方法。从而达到我们可以根据传递的子类对象而实现不一样的业务处理。
    java的回调机制的原理,用很有吸引的一个标题讲解,就像是好莱坞原则一样:Don't call me,I will call you.讲的是:应聘者不用找公司方,当公司方需要你这个演员时,会自己找到你的。
编程上来说,一般使用一个库或类时,是程序员去调用事先定义好的API,这个叫Call。有的时候这样不能满足需要,需要程序员注册自己的程序(比如一个对象),然后让事先定义好的API在合适的时候来调用程序员写的方法,这叫Callback。
回调,从字面上我们可以看出,这是一种双向调用模式。被调用方在接口被调用时也会调用对方的接口。
技巧在于:定义一个简单的接口,并在接口中声明我们要调用的方法。
    举例如下所示:
定义的接口:
public interface InterestingEvent {
   public void interestingEvent();
}
实现接口的代码如下:
public class CallMe implements InterestingEvent {
       public CallMe() {
   }

   public void interestingEvent() {
       System.out.println("实现了打印!")
  }
}
public class CallYou implements InterestingEvent {
      public CallYou() {
   }

public void interestingEvent() {
 
     System.out.println("实现了查询!");
}

}
发出事件信号的类必须等待实现了 InterestingEvent 接口的对象,并在适当时候调用 interestingEvent() 方法。
public class EventNotifier {
private InterestingEvent ie;
private boolean somethingHappened ;
public EventNotifier() {
 somethingHappened = true ;
}
public void setInterestingEvent(InterestingEvent ie){
 this.ie = ie ;
}
public void doWork(){
 if(somethingHappened){
  ie.interestingEvent();
 }
}

}
测试:
public class Test {
public static void main(String[] args) {
 CallMe cm = new CallMe();
 CallYou cy = new CallYou();
 EventNotifier en = new EventNotifier();

 en.setInterestingEvent(cm);
 en.doWork();
 en.setInterestingEvent(cy);
 en.doWork();
}
}


原创粉丝点击