Java自定义事件

首先,要清晰事件的参与者:
1、事件(Event),自定义事件均继承自EventObject
2、监听者(Listener),监听者均继承自EventListener
3、触发对象,如Button等,这里的触发对象显然是我们的自定义对象

定义事件
public class BaseEvent extends EventObject {
	private static final long serialVersionUID = 1L;
	private Object obj;

	public BaseEvent(Object source) {
		super(source);
		this.obj=source;
	}
	
	@Override
	public Object getSource()
	{
		return this.obj;
	}
}

定义监听者,它是一个接口,里面包含一个自定义的方法
public interface BaseEventListener extends EventListener {
	public void processEvent(BaseEvent event);
}

触发对象,BaseEvent事件的触发和监听,均是通过EventBus对象完成的。
public class EventBus {
	private Vector rep=new Vector();
	BaseEventListener listener;
	public void addBaseEventListener(BaseEventListener bl)
	{
		rep.addElement(bl);
	}
	
	public void notifyBaseEvent(Object obj)
	{
		Enumeration e=rep.elements();
		while(e.hasMoreElements())
		{
			listener=(BaseEventListener) e.nextElement();
			listener.processEvent(new BaseEvent(obj));
		}
	}

}


最后写一段测试代码
	public static void main(String args[])
	{
		EventBus bus=new EventBus();
		bus.addBaseEventListener(new BaseEventListener()
		{
			@Override
			public void processEvent(BaseEvent event) {
				System.out.println(event.getSource());
				
			}
			
		});
		//触发事件
		bus.notifyBaseEvent("test event is ok!");	
	}


最后打印输出 test event is ok! 当然也可以将任意Object对象当做事件响应后的结果。


-----------------------EventBus升级版-----------------------------
将EventBus做成Static
public class EventBus {
	private static EventBus bus=new EventBus();
	private Vector<BaseEventListener> rep=new Vector<BaseEventListener>();
	BaseEventListener listener;
	public void addBaseEventListener(BaseEventListener bl)
	{
		rep.addElement(bl);
	}
	
	public void notifyBaseEvent(Object obj)
	{
		Enumeration<BaseEventListener> e=rep.elements();
		while(e.hasMoreElements())
		{
			listener=(BaseEventListener) e.nextElement();
			listener.processEvent(new BaseEvent(obj));
		}
	}
	public static EventBus getInstance()
	{
		return bus;
	}

}

你可能感兴趣的:(java)