在Java中实现回调过程

摘要:
  Java接口提供了一个很好的方法来实现回调函数。假如你习惯于在事件驱动的编程模型中,经过传递函数指针来调用方法达到目的的话,那么你就会喜欢这个技巧。
  
   做者:John D. Mitchell
  
  在MS-Windows或者X-Window系统的事件驱动模型中,当某些事件发生的时候,开发人员已经熟悉经过传递函数指针来调用处理方法。而在Java的面向对象的模型中,不能支持这种方法,于是看起来彷佛排除了使用这种比较温馨的机制,但事实并不是如此。
  
  Java的接口提供了一种很好的机制来让咱们达到和回调相同的效果。这个诀窍就在于定一个简单的接口,在接口之中定义一个咱们但愿调用的方法。
  
  举个例子来讲,假设当一个事件发生的时候,咱们想它被通知,那么咱们定义一个接口:
  public interface InterestingEvent
  {
    // This is just a regular method so it can return something or
    // take arguments if you like.
    public void interestingEvent ();
  }
  
  这就给咱们一个控制实现了该接口的全部类的对象的控制点。所以,咱们不须要关心任何和本身相关的其它外界的类型信息。这种方法比C函数更好,由于在C++风格的代码中,须要指定一个数据域来保存对象指针,而Java中这种实现并不须要。
  
  发出事件的类须要对象实现InterestingEvent接口,而后调用接口中的interestingEvent ()方法。
  
  public class EventNotifier
  {
    private InterestingEvent ie;
  private boolean somethingHappened;
    public EventNotifier (InterestingEvent event)
  {
  // Save the event object for later use.
  ie = event;
  // Nothing to report yet.
  somethingHappened = false;
  }
    //... 
    public void doWork ()
  {
  // Check the predicate, which is set elsewhere.
  if (somethingHappened)
    {
    // Signal the even by invoking the interface's method.
    ie.interestingEvent ();
    }
  //...
    }
    // ...
  }
  
  在这个例子中,咱们使用了somethingHappened这个标志来跟踪是否事件应该被激发。在许多事例中,被调用的方法可以激发interestingEvent()方法才是正确的。
  但愿收到事件通知的代码必须实现InterestingEvent接口,而且正确的传递自身的引用到事件通知器。
  public class CallMe implements InterestingEvent
  {
  private EventNotifier en;
    public CallMe ()
  {
  // Create the event notifier and pass ourself to it.
  en = new EventNotifier (this);
  }
    // Define the actual handler for the event.
    public void interestingEvent ()
  {
  // Wow! Something really interesting must have occurred!
  // Do something...
  }
    //...
  }
  
  但愿这点小技巧能给你带来方便。
  
   关于做者:   John D. Mitchell在过去的九年内一直作顾问,曾经在Geoworks使用OO汇编语言开发了PDA软件,爱好于写编译器,Tcl/Tk和Java系统。和人合著了《Making Sense of Java》,目前从事Java编译器的工做。
相关文章
相关标签/搜索