您的位置:首页 > 编程语言 > Java开发

Java 事件触发接口回调方法

2011-09-02 16:52 369 查看
其技巧就是:定义一个简单接口,并在该接口中声明我们要调用的方法,一般可以应用在键盘鼠标事件跟踪。

下面举一个例子:

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

/*

* 在某个事件发生时得到通知.

*/

public interface InterestingEvent {

   public void interestingEvent(); //其它方法体及方法定义也可.

}

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

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

实现接口的代码如下:

public class CallMe implements InterestingEvent {

public CallMe() {

   }

   public void interestingEvent() {

   System.out.println("发生了CallMe事件,哈哈");

  }

}

public class CallYou implements InterestingEvent {

public CallYou() {

  }

public void interestingEvent() {

System.out.println("发生了CallYou事件,哈哈");

}

}

发出事件信号的类必须等待实现了 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 事件驱动编程模型.

实际上采用了接口回调引用对象类,从而此对象实现方法调用.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: