Java 事件驱动模式介绍
在一个类 Class1 中写一个事件 event1,
当 Class1 中的某个值变化时,就触发 event1,
然后写另外一个类 Class2,监听 Class1 中的 event1 事件,
public class A{
private Vector aListeners = new Vector();
private int value;
public int getValue(){
return value;
}
public void setValue(int newValue){
if(value!=newValue){
value = newValue;
AEvent evt= new AEvent(this,value);
//如果值改变的话,
就触发事件
fireAEvent(evt);
}
}
public synchronized void addAListener(AListener a){
aListeners.addElement(a);
}
public synchronized void removeAListener(Alistener a){
aListeners.removeElement(a);
}
public void fireAEvent(AEvent evt){
Vector currentListeners = null;
synchronized(this){
currentListeners = (Vector)aListeners.clone();
}
for(int i =0;i<currentListeners.size();i++){
AListener listener = (AListener)currentListeners.elementAt(i);
listener.performed(evt);
}
}
}
//定义接口,
当事件触发时调用
public interface AListener extends java.util.EventListener{