Java 的Event机制浅析

通常Java添加监听类似C里面的回调,通常在使用时比较简单,自己定义的事件类(继承EventObject),定义监听器接口(继承EventListener),定义一个者向量来保存添加的这些监听器,通过addListenerremoveListener来操作。

但是监听器如何被触发的,从底层消息到启动监听器的流程是什么样子的?

将分篇来说明,下面以一个BossXi ,BossLi类来说明:

添加EmployeeEvent事件类:

package Company;

import java.util.EventObject;

public class EmployeeEvent extends EventObject{
 private int m_nReason;

private int m_nType;

private Object m_sSource;

public EmployeeEvent(Object arg0,int reason , int type) {
  super(arg0);
  // TODO Auto-generated constructor stub
  this.setType(type);
  this.m_nReason = reason;
  this.m_sSource = arg0;
 }

/**
  *
  */
 private static final long serialVersionUID = 1L;

public static final int EVENT_WORK_ON = 0;
 
 public static final int EVENT_WORK_OFF = 1;
 
 public int getReason(){ 
  return m_nReason; 
 }
 
 public int getType(){
  return m_nType;
 }
 
 public int setType(int nType){
  return this.m_nType = nType;
 }
 
 public Object getSource(){
  return (java.lang.Object)m_sSource;
 }
}

添加EmployeeListener监听接口:

package Company;

// 实现 EventListener接口
public interface EmployeeListener extends java.util.EventListener{

// 使用监听器的时候,实现并添加到
 public void onEmPloyeeEvent(EmployeeEvent empEvent);
 
}

添加分发消息接口MessageHandler:

package Company;

public interface MessageHandler {
 
  public void processMessage(Message message);
 
}

添加消息Message类:

package Company;

public class Message {
  public final static int TerminateType = -1;
  public int type;
  public Object data;
  MessageHandler handler;

public Message(MessageHandler p, int t, Object d)
  {
    handler = p;
    type = t;
    data = d;
  }

public boolean equals(Object o)
  {
    Message e = (Message) o;
    return ((handler == e.handler) && (type == e.type) &&
            data.equals(e.data));
  }
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/3188e1d8c790b5784ed00e489fefe683.html