事件——監聽器模式

http://www.cnblogs.com/zuoxiaolong/p/pattern7.htmlhtml

 想研究 湯姆貓,發現裏面不少監聽器 : 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接口

相關文章
相關標籤/搜索