首页 > 代码库 > 设计模式之监听器模式

设计模式之监听器模式

事件处理模型:


组件(事件源)不处理自己的事件,而是将事件处理委托给外部的处理实体(监听器,

这种事件处理模型称为事件的 授权处理模型。

不同的事件,可以交由不同类型的监听器去处理


事件源:


提供订阅与取消监听者的方法,并负责维护监听者列表,发送事件给监听者


监听者:


每个监听者实现接口来接收事件,并负责从事件源订阅与取消订阅



图示:





demo


事件源:

Context:


package com.demo.event;

import java.util.ArrayList;
import java.util.List;

public class Context {
	private static List<Listener> list=new ArrayList<Listener>();
	public static void addListener(Listener listener){
		list.add(listener);
	}
	public static void removeListener(Listener listener){
		list.remove(listener);
	}
	public static void sendNotification(Event event){
		for(Listener listener:list){
			listener.onChange(event);
		}
	}
}

监听者:

Listener

package com.demo.event;

public interface Listener {
	public void onChange(Event event);
}

MyListener


package com.demo.event;

public class MyListener implements Listener {

	@Override
	public void onChange(Event event) {
		switch(event.getType()){
			case Event.INSTALLED:
				System.out.println("do install...");
				break;
			case Event.STARTED :
				System.out.println("do started...");
				break;
			case Event.RESOLVED :
				System.out.println("do resolved...");
				break;
			case Event.STOPPED :
				System.out.println("do stopped...");
				break;
			case Event.UNRESOLVED :
				System.out.println("do unresolved...");
				break;
			case Event.UNINSTALLED :
				System.out.println("do uninstalled...");
				break;
			default:
				throw new IllegalArgumentException();
		}
	}

}

事件:

package com.demo.event;

public class Event {
	public static final int INSTALLED =1; 
	public static final int STARTED =2; 
	public static final int RESOLVED  =3; 
	public static final int STOPPED =4; 
	public static final int UNRESOLVED  =5; 
	public static final int UNINSTALLED   =6;
	private int type ;
	private Object source ;
	public Event(int type, Object source) {
		this.type = type;
		this.source = source;
	}
	public int getType() {
		return type;
	}
	public Object getSource() {
		return source;
	}
}


测试:

package com.demo.event;

public class EventTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Listener listener=new MyListener();
		//添加监听者
		Context.addListener(listener);
		//模拟bundle安装完成事件触发
		Context.sendNotification(new Event(Event.INSTALLED, new MyBundle()));
	}

}



设计模式之监听器模式