JDK当中依然有现成的一套事件模型类库,其中监听器只是一个标识接口,因为它没有表达对具体对象感兴趣的意思,所以也无法定义监听的事件,只是为了统一,用来给特定的监听器继承。它的源代码如下。
[java]
package java.util;
/**
* A tagging interface that all event listener interfaces must extend.
* @since JDK1.1
*/
public interface EventListener {
}
package java.util;
/**
* A tagging interface that all event listener interfaces must extend.
* @since JDK1.1
*/
public interface EventListener {
} 由于代码很短,所以LZ没有删减,当中标注了,所有的事件监听器都必须继承,这是一个标识接口。上述的事件,JDK当中也有一个现成的类供继承,就是EventObject,这个类的源代码如下。
[java]
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 + "]";
}
}
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 + "]";
}
} 这个类并不复杂,它只是想表明,所有的事件都应该带有一个事件源,大部分情况下,这个事件源就是我们被监听的对象。
如果我们采用事件驱动模型去分析上面的例子,那么作者就是事件源,而读者就是监听器,依据这个思想,我们把上述例子改一下,首先我们需要自定义我们自己的监听器和事件。所以我们定义如下作者事件。
[java]
import java.util.EventObject;
public class WriterEvent extends EventObject{
private static final long serialVersionUID = 8546459078247503692L;
public WriterEvent(Writer writer) {
super(writer);
}
public Writer getWriter(){
return (Writer) super.getSource();
}
}
import java.util.EventObject;
public class WriterEvent extends EventObject{
private static final long serialVersionUID = 8546459078247503692L;
public WriterEvent(Writer writer) {
super(writer);
}