当前页面: JAVA 编程资料牛鼻论坛 → Java & J2SE 技术区→Java事件驱动模式 |
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{ public abstract void performed(AEvent e); } //定义事件 public class AEvent extends EventObject{ private int value; public AEvent(Object source){ this(source,null); } public AEvent(Object source,int newValue){ super(source); value = newValue; } } class B{ public B(){ A a = new A(); a.addAListener(new AListener(){ public performed(AEvent e){ //要处理的 } }); } }