想研究 汤姆猫,发现里面不少监听器 : LifecycleEvent,Lifecycle,ServletContextListener(Spring)等,故做此文。java
java在gui方面用到了大量该模式,当初上大学时用过swing,awt,如今全忘了。有兴趣的能够深究一下。编程
事件-监听器模式须要四个类:事件源,事件,监听器(interface),具体的监听器ui
事件源产生事件,如窗口产生点击、关闭事件。this
监听器是具体监听器的抽象,面向接口的编程。事件源不须要知道监听器的具体实现细节,只需调用抽要便可。code
jdk已有该模式的规范,htm
//监听器接口 package java.util; public interface EventListener { } //事件 package java.util; /** * <p> * The root class from which all event state objects shall be derived. * <p> * All Events are constructed with a reference to the object, the "source", * that is logically deemed to be the object upon which the Event in question * initially occurred upon. * * @since JDK1.1 */ public class EventObject implements java.io.Serializable { private static final long serialVersionUID = 5516075349620653480L; /** * The object on which the Event initially occurred. */ protected transient Object source; /** * Constructs a prototypical Event. * * @param source The object on which the Event initially occurred. * @exception IllegalArgumentException if source is null. */ public EventObject(Object source) { if (source == null) throw new IllegalArgumentException("null source"); this.source = source; } /** * The object on which the Event initially occurred. * * @return The object on which the Event initially occurred. */ public Object getSource() { return source; } /** * Returns a String representation of this EventObject. * * @return A a String representation of this EventObject. */ public String toString() { return getClass().getName() + "[source=" + source + "]"; } }
这个监听器是个空接口,咱们能够本身定义一个EventList接口,包含一个void onEvent(ConcreateEventObject eventObject)方法。blog
本文头部的连接写的很好,读者能够点进去细读。thanks接口