参照 https://www.cnblogs.com/lichmama/p/8976092.html
模型:
事件Event、事件源Source、监听器Listener
事件源注册监听器、事件传入事件源。事件发生,通知监听器,监听器处理
demo:
事件Event:
public class Event { private Source source; public Event(Source source) { if(source == null) throw new IllegalArgumentException("null source"); this.source = source; } public Source getSource() { return source; } }
事件源Source:
public class Source { private String name; public void setName(String name){ this.name = name; } public String getName() { return name; } private Set<EventListener> listenerSet = new HashSet<>(); public void registerEventListener(EventListener eventListener){ if (eventListener != null){ listenerSet.add(eventListener); } } public void handle(){ for (EventListener eventListener : listenerSet) { ThreadPoolUtil.execute(()-> { Event event = new Event(this); eventListener.callback(event); }); } } }
监听器Listener
public interface EventListener { void callback(Event e); }
测试
public class App { public static void main(String[] args) { Source source = new Source(); source.setName("av"); source.registerEventListener((event)->{ System.out.println("one...."); System.out.println(event.getSource().getName()); System.out.println(Thread.currentThread().getName()); }); source.registerEventListener((event)->{ System.out.println("two...."); System.out.println(event.getSource().getName()); System.out.println(Thread.currentThread().getName()); }); source.handle(); } }
结果:
two.... av pool-1-thread-1 one.... av pool-1-thread-2