日期:2014-05-20 浏览次数:20644 次
public interface EventHandler { void execute(String event,Object... parameters); } public class EventContext { private static Map<String, Set<EventHandler>> EVENT_HANDLER_REGISTER = new HashMap<String, Set<EventHandler>>(); public static void fireEvent(String event, Object... parameters) { Set<EventHandler> handlers = EVENT_HANDLER_REGISTER.get(event); if (handlers != null) { for (EventHandler handler : handlers) { handler.execute(event, parameters); } } } public static void registerEventHandler(String event, EventHandler handler) { Set<EventHandler> handlers = EVENT_HANDLER_REGISTER.get(event); if (handlers == null) { handlers = new HashSet<EventHandler>(); EVENT_HANDLER_REGISTER.put(event, handlers); } handlers.add(handler); } public static Set<EventHandler> getEventHandlers(String event) { return EVENT_HANDLER_REGISTER.get(event); } } public class A { void doSomething(){ //do something EventContext.fireEvent("somethingDone","some value from A"); } } public class B implements EventHandler { @Override public void execute(String event,Object... parameters) { System.out.println("I'm running with "+ parameters[0]); } } public class Test { public static void main(String[] args) { A a=new A(); B b=new B(); EventContext.registerEventHandler("somethingDone",b); a.doSomething(); } }
------解决方案--------------------
簡單點就是觀察者模式,給一個簡單的sample
interface Observer{ void ChangeEvent(); } class A{ private Observer ob; A(){ ob = null; } void SetObserver(Observer ob){ this.ob = ob; } void InvokeB(){ if (ob != null) ob.ChangeEvent(); } } class B implements Observer{ public void ChangeEvent(){ System.out.println("B is invoked"); } } public class ObserverTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub A a = new A(); a.SetObserver(new B()); a.InvokeB(); } }