服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

在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编译器的工作。

扫描关注微信公众号