看项目代码时遇到了好多事件监听机制相关的代码。现学习一下:
java事件机制包含三个部分:事件、事件监听器、事件源。
1.事件:继承自java.util.EventObject类,开发人员自己定义。
package com.shuyan.javatest.EventTest; import java.util.EventObject; public class DnsEvent extends EventObject { private String userData; private long parseTime; public DnsEvent(Object source) {
super(source);
} public DnsEvent(Object source, String userData, long parseTime) {
super(source);
this.userData = userData;
this.parseTime = parseTime;
} public String getUserData() {
return userData;
} public void setUserData(String userData) {
this.userData = userData;
} public long getParseTime() {
return parseTime;
} public void setParseTime(long parseTime) {
this.parseTime = parseTime;
} }
2.事件监听器:实现java.util.EventListener接口,注冊在事件源上,当事件源的属性或状态改变时,取得对应的监听器调用其内部的回调方法。
package com.shuyan.javatest.EventTest; import java.util.EventListener; public interface DnsEventListener extends EventListener { public void processDnsEvent(DnsEvent dnsEvent); }
监听器的详细实现类
public class DnsEventaListenerImpl implements DnsEventListener { @Override
public void processDnsEvent(DnsEvent dnsEvent) { String userdata = dnsEvent.getUserData();
System.out.println("userdata-->" + userdata); }
}
3.事件源:事件发生的地方,因为事件源的某项属性或状态发生了改变导致某项事件发生。因为事件监听器要注冊在事件源上,所以事件源类中应该要有盛装监听器的容器(List,Set等)。
public class ManagerListener { private List<DnsEventListener> listeners = null; private static class Singleton {
static ManagerListener managerListener = new ManagerListener();
} public static ManagerListener getInstance() {
return Singleton.managerListener;
} private ManagerListener() {
listeners = new ArrayList<>();
} public void addDnsEventListener(DnsEventListener listener) {
this.listeners.add(listener);
} public void removeDnsEventListener(DnsEventListener listener) {
this.listeners.remove(listener);
} public void fireDnsEventListener(DnsEvent event) {
for (DnsEventListener listener : listeners) {
listener.processDnsEvent(event);
}
} }
測试例如以下:
public class DnsEventTest {
public static void main(String[] args) {
ManagerListener managerListener = ManagerListener.getInstance();
DnsEvent dnsEvent = new DnsEvent(managerListener, "data", 1000L);
DnsEventaListenerImpl listener = new DnsEventaListenerImpl(); managerListener.addDnsEventListener(listener);
managerListener.fireDnsEventListener(dnsEvent);
}
}
參考:http://blog.csdn.net/longlong3050/article/details/6854456