Java 事件處理遵循「觀察者模式」,包含三大核心角色:
java.util.EventObject,封裝事件源與上下文信息java.util.EventListener,定義回調方法// 事件對象
public class PropertyEvent extends EventObject {
private final String propertyName;
private final Object oldValue, newValue;
public PropertyEvent(Object source, String propertyName, Object oldValue, Object newValue) {
super(source);
this.propertyName = propertyName;
this.oldValue = oldValue;
this.newValue = newValue;
}
// getter 省略
}
// 監聽器接口
public interface PropertyListener extends EventListener {
void propertyChanged(PropertyEvent event);
}
import java.util.*;
public class Exam {
private int property;
private final Set listeners = Collections.synchronizedSet(new HashSet<>());
public void addListener(PropertyListener listener) {
listeners.add(listener);
}
public void removeListener(PropertyListener listener) {
listeners.remove(listener);
}
public void setProperty(int newValue) {
int oldValue = this.property;
this.property = newValue;
firePropertyChange(new PropertyEvent(this, "property", oldValue, newValue));
}
private void firePropertyChange(PropertyEvent event) {
// 複製快照避免迭代時併發修改
List snapshot;
synchronized (listeners) {
snapshot = new ArrayList<>(listeners);
}
for (PropertyListener listener : snapshot) {
listener.propertyChanged(event);
}
}
}
exam.addListener(this); 當前類實現 PropertyListenerexam.addListener(event -> {
System.out.println("屬性變更:" + event.getPropertyName());
});GUI 事件在 EDT 中分發,監聽器代碼必須快速返回,耗時操作需提交至工作線程(SwingWorker)。
大型系統可引入 Guava EventBus、Spring ApplicationEvent 或 MBassador 實現跨組件異步事件傳遞,降低耦合度。
使用 WeakReference 包裝監聽器,避免事件源持有強引用導致監聽器無法被 GC 回收。