歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

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.linuxidc.com/Linux/2014-05/101046p2.htm

Copyright © Linux教程網 All Rights Reserved