package com.event;
/**
* 事件
*/
public class Event {
/**发起事件的对象*/
private Object source;
/**事件类型*/
private int type;
/**参数*/
private Object[] args;
public Event(int type, Object ...args){
this.type = type;
this.args = args;
}
public Object getSource() {
return source;
}
void setSource(Object source){
this.source = source;
}
public int getType() {
return type;
}
public Object[] getArgs() {
return args;
}
}
------------------------------------------------
package com.event;
/**
*
* 事件监听器
*
*/
public interface EventListener {
/**
*
* @param event
* @throws Exception
*/
public void eventPerformed(Event event) throws Exception;
}
------------------------------------------------
package com.event;
import java.util.HashMap;
import java.util.Map;
/**
*
* 事件派发器
*
*/
public abstract class EventDispatcher {
/**{key=EventType,value={key=被监听对象,value=EventListeners}}*/
private Map<Integer, EventListener> listeners;
public EventDispatcher(){
listeners = new HashMap<Integer, EventListener>();
}
/**
*
* @param eventType 事件类型
* @param target 被监听对象
* @param listener 监听器
* @throws Exception
*/
public void addListener(int eventType, EventListener listener) throws Exception{
/**添加监听器,事件类型必须是注册过的*/
listeners.put(eventType, listener);
}
/**
* 移除事件监听器
* @param evenType 事件类型
* @param target 被监听对象
*/
public void removeListener(int eventType){
listeners.remove(eventType);
}
/**
* 触发事件
* @param event
* @return
*/
public boolean dispatchEvent(Event event) throws Exception{
EventListener listener = listeners.get(event.getType());
if(listener != null){
event.setSource(this);
listener.eventPerformed(event);
return true;
}
return false;
}
}
------------------------------------------------
测试类:
package com.event.test;
import com.event.Event;
import com.event.EventDispatcher;
import com.event.EventListener;
public class EventTest extends EventDispatcher{
public final static int LOGIN = 1;
public final static int LOGOUT = 2;
public EventTest() throws Exception{
EventListener listener = null;
listener = new EventListener(){
public void eventPerformed(Event event){
login(event);
}
};
this.addListener(LOGIN, listener);
listener = new EventListener(){
public void eventPerformed(Event event){
logout(event);
}
};
this.addListener(LOGOUT, listener);
}
public void login(Event event){
System.out.println((String)event.getArgs()[0] + " login...");
}
public void logout(Event event){
System.out.println((String)event.getArgs()[0] + " logout...");
}
public static void main(String args[]) throws Exception{
EventTest test = new EventTest();
test.dispatchEvent(new Event(EventTest.LOGIN, "admin"));
test.dispatchEvent(new Event(EventTest.LOGOUT, "admin"));
test.removeListener(EventTest.LOGIN);
test.dispatchEvent(new Event(EventTest.LOGIN, "admin"));
test.dispatchEvent(new Event(EventTest.LOGOUT, "admin"));
}
}
测试结果:
admin login...
admin logout...
admin logout...