java事件机制的参与者:
event object:事件对象,时间产生时具体的“事件”,一般作为listener的方法参数使用。
event source:事件源,接收事件的实体。
event listener:事件监听器类。当有对应的event object产生时,调用相应的方法进行处理。
事件对象:
/**
* 事件对象类
* 继承EventObject类
*/
public class DoorEvent extends EventObject{
private static final long serialVersionUID = 6734613668785304327L;
private String state;
public DoorEvent(Object source, String state) {
super(source);
this.state = state;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
事件监听器:
/**
* 事件监听器接口类
* 继承EventListener接口
*/
public interface DoorEventListener extends EventListener{
public void fireEvent(DoorEvent event);
}
/**
* 开门事件监听器类
*/
public class DoorOpenEventListener implements DoorEventListener {
@Override
public void fireEvent(DoorEvent event) {
if("open".equals(event.getState())){
System.out.println("Door opened");
}
}
}
/**
* 关门事件监听器类
*/
public class DoorCloseEventListener implements DoorEventListener {
@Override
public void fireEvent(DoorEvent event) {
if("close".equals(event.getState())){
System.out.println("Door closed!");
}
}
}
事件源:
/**
* 事件源类
*/
public class DoorManager {
private Set<DoorEventListener> listeners = new HashSet<DoorEventListener>();
/**
* 注册事件
*/
public void addListener(DoorEventListener listener){
listeners.add(listener);
}
/**
* 删除事件
*/
public void removeListener(DoorEventListener listener){
listeners.remove(listener);
}
/**
* 通知所有注册的事件
* @param event 事件对象
*/
private void notifyListeners(DoorEvent event){
Iterator<DoorEventListener> it = listeners.iterator();
while (it.hasNext()) {
DoorEventListener listener = (DoorEventListener) it.next();
listener.fireEvent(event);
}
}
public void openDoor(){
DoorEvent event = new DoorEvent(this, "open");
notifyListeners(event);
}
public void closeDoor(){
DoorEvent event = new DoorEvent(this, "close");
notifyListeners(event);
}
public static void main(String[] args) {
DoorManager dm = new DoorManager();
dm.addListener(new DoorOpenEventListener());
dm.addListener(new DoorCloseEventListener());
dm.openDoor();
dm.closeDoor();
}
}