lzzzing学习笔记

正在学的和想要学的

   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  44 随笔 :: 7 文章 :: 17 评论 :: 0 Trackbacks

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

下面举一个例子:

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

/*
 * 在某个事件发生时得到通知.
 */
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 事件驱动编程模型.

posted on 2008-05-15 22:16 lzzzing 阅读(133) 评论(0)  编辑 收藏 引用 所属分类: Java


标题  
姓名  
主页
验证码 *
内容(提交失败后,可以通过“恢复上次提交”恢复刚刚提交的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
[使用Ctrl+Enter键可以直接提交]