2008-05-15

JAVA回调机制

其技巧就是:定义一个简单接口,并在该接口中声明我们要调用的方法。

下面举一个例子:

假定我们希望在某个事件发生时得到通知。我们可以定义一个接口:

/*
 * 在某个事件发生时得到通知.
 */
public interface InterestingEvent {
   public void interestingEvent();
}

此接口中的方法,是个没有返回值的也没有任何参数,如果您愿意也可以有返回值,也可以带参数.这就要看具体需求而定.

这使得我们可以控制实现该接口的类的任何对象。因此,我们不必关心任何外部类型信息。与在将 C++ 代码用于Motif 时使用窗口小部件的数据域来容纳对象指针的难以控制的 C 函数相比,这种方法要好得多。

实现接口的代码如下:

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 {

 /**
  * @param args
  */
 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();
 }

}

此测试在发生指定的调用CalMe事件时,就扫行CallMe下的命令,如发生CallYou事件时,就调用CallYou下的命令.此种方法可以结合Command模式.实现MS-Windows 和 X Window System 事件驱动编程模型.

评论
sunxg 2008-05-15
代码看的明白,但是思想不是很明白......
发表评论

您还没有登录,请登录后发表评论

Jatula
搜索本博客
我的相册
最近加入圈子
存档
最新评论