public class EventBus { private static Map<String, EventListener> eventListeners = new HashMap<>(); public static void addEventListener(EventListener listener) {
String listenerName = getListenerName(listener);
eventListeners.put(listenerName, listener);
} public static void removeEventListener(EventListener listener) {
String listenerName = getListenerName(listener);
eventListeners.remove(listenerName);
} public static void sendEvent(Event event) {
Collection<EventListener> listeners = eventListeners.values();
for (EventListener listener : listeners) {
if (listener != null) {
listener.onEvent(event);
}
}
} private static String getListenerName(TMSEventListener listener) {
String listenerName = listener.getName();
if (StringUtils.isBlank(listenerName)) {
listenerName = listener.getClass().getName();
}
return listenerName;
} }
public interface EventListener { /**
* 监听到事件后会调用此函数
* @param event
*/
public void onEvent(Event event); /**
* 事件监听器的唯一名字
* @return 字符串
*/
public String getName();
}
public class Event { private String name;
private Object data; public Event() {
} public Event(String name,Object data) {
this.data = data;
this.name = name;
} public Object getData() {
return data;
} public void setData(Object data) {
this.data = data;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} }