1、定义一个 ValueChangedEvent
ValueChangedEvent用于在设置属性值的时候,触发事件。
package org.teamlet; import java.util.EventObject; public class ValueChangeEvent extends EventObject { /** * */ private static final long serialVersionUID = 767352958358520268L; private int value; public ValueChangeEvent(Object source) { this(source, 0); } public ValueChangeEvent(Object source, int newValue) { super(source); value = newValue; } public int getValue() { return value; } }
ValueChangeListener 提供属性值变化的接口。
package org.teamlet; public interface ValueChangeListener extends java.util.EventListener { public abstract void performed(ValueChangeEvent e); }
3、事件的产生者
EventProducer提供了监听容器listenerRegister,负责消费者的注册。
package org.teamlet; public class EventProducer { ListenerRegister register = new ListenerRegister(); private int value; public int getValue() { return value; } public void setValue(int newValue) { if (value != newValue) { value = newValue; ValueChangeEvent event = new ValueChangeEvent(this, value); fireAEvent(event); } } public void addListener(ValueChangeListener a) { register.addListener(a); } public void removeListener(ValueChangeListener a) { register.removeListener(a); } public void fireAEvent(ValueChangeEvent event) { register.fireAEvent(event); } }
ListenerRegister负责注册和分发事件。
package org.teamlet; import java.util.Vector; public class ListenerRegister { private Vector<ValueChangeListener> listeners = new Vector<ValueChangeListener>(); public synchronized void addListener(ValueChangeListener a) { listeners.addElement(a); } public synchronized void removeListener(ValueChangeListener a) { listeners.removeElement(a); } @SuppressWarnings("unchecked") public void fireAEvent(ValueChangeEvent evt) { Vector<ValueChangeListener> currentListeners = null; synchronized (this) { currentListeners = (Vector<ValueChangeListener>) listeners.clone(); } for (int i = 0; i < currentListeners.size(); i++) { ValueChangeListener listener = (ValueChangeListener) currentListeners .elementAt(i); listener.performed(evt); } } }
EventConsumer实现ValueChangedListener,当EventProducer 发送事件时,接收事件。
package org.teamlet; public class EventConsumer implements ValueChangeListener { @Override public void performed(ValueChangeEvent e) { System.out.println("value changed, new value = " + e.getValue()); } }
package org.teamlet; public class Main { public static void main(String[] args) { EventProducer producer = new EventProducer(); producer.addListener(new EventConsumer()); producer.setValue(2); } }