想研究 汤姆猫,发现里面很多监听器 : LifecycleEvent,Lifecycle,ServletContextListener(Spring)等,故作此文。
java在gui方面用到了大量该模式,当初上大学时用过swing,awt,现在全忘了。有兴趣的可以深究一下。
事件-监听器模式需要四个类:事件源,事件,监听器(interface),具体的监听器
事件源产生事件,如窗口产生点击、关闭事件。
监听器是具体监听器的抽象,面向接口的编程。事件源不需要知道监听器的具体实现细节,只需调用抽要即可。
jdk已有该模式的规范,
//监听器接口package java.util;public interface EventListener {}//事件package java.util;/** ** The root class from which all event state objects shall be derived. *
* 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)方法。
本文头部的链接写的很好,读者可以点进去细读。thanks