之前写过自己的js框架,有比较完善的事件体系。当后台java代码用到类似功能时,发现写法相当繁琐,就开发了一个简单的事件系统。
用法如下:
1、定义监听器
public class PageRequestListener implements IListener {
@Override
public void execute(Event event) {
//request为event的自定义属性
HttpServletRequest request=event.getProperty("request");
/*代码*/
}
}
2、添加监听
//第一个参数是事件名称,第二个参数是监听器,IListener的实现类
Observable.addListener("PageRequest",new PageRequestListener());
3、触发事件
//Event第一个参数是事件名称,第二个参数是eventSource,可选。addProperty方法增加事件对象的自定义属性,可以链式调用。此处是增加的一个request对象
Observable.fireEvent(new Event("PageRequest").addProperty("request",request));
下边贴上源码,包含三个类,分别是Observable、IListener、Event
1、Observable
public class Observable {
private static Map<String,List<IListener>> listeners=new HashMap<String,List<IListener>>();
public static void addListener(String type,IListener ls){
List<IListener> lsList= listeners.get(type);
if(lsList==null){
lsList=new ArrayList<IListener>();
listeners.put(type,lsList);
}
lsList.add(ls);
}
public static void fireEvent(Event event){
String type=event.getType();
List<IListener> lsList= listeners.get(type);
if(lsList!=null){
for(IListener ls:lsList){
ls.execute(event);
}
}
}
}
2、IListener
public interface IListener extends EventListener {
public void execute(Event e);
}
3、Event
public class Event extends EventObject {
private String type;
private Map<String, Object> properties;
public Event(String type, Object source) {
super(source);
this.type = type;
}
public Event(String type) {
super("none");
this.type = type;
}
public Event(Object source, String type, Map<String, Object> properties) {
super(source);
this.type = type;
this.properties = properties;
}
public String getType() {
return type;
}
public <T> T getProperty(String key) {
return properties != null ? (T) properties.get(key) : null;
}
public Event addProperty(String key, Object value) {
if (this.properties == null) {
this.properties = new HashMap<String, Object>();
}
this.properties.put(key, value);
return this;
}
}