Java观察者模式(Java事件监听)

分类:软件编程
阅读:871
作者:majingjing
发布:2017-03-19 16:26

利用Java的观察者模式编写一个简单的Java事件监听案例

图不重要,看代码。 timg.jpg

下面直接编写代码

package cn.majingjing.tzx.event;

public interface EntryListener {
	
	public abstract void entryAdded(EntryEvent entryevent);

	public abstract void entryDeleted(EntryEvent entryevent);

	public abstract void entryModified(EntryEvent entryevent);

}

package cn.majingjing.tzx.event;

public class Entry {

	private long id;
	private String name;
	
	...省略get,set方法
}
package cn.majingjing.tzx.event;

import java.util.Collections;
import java.util.Date;
import java.util.Map;

public class EntryEvent {

	public static final int ENTRY_ADDED = 100;
	public static final int ENTRY_DELETED = 101;
	public static final int ENTRY_MODIFIED = 102;

	private int eventType;
	private Entry entry;
	private Date date;
	private Map<?, ?> params;

	public EntryEvent(int eventType, Entry entry, Map<?, ?> params) {
		this.eventType = eventType;
		this.entry = entry;
		this.params = params != null ? Collections.unmodifiableMap(params) : null;
		date = new Date();
	}

	public int getEventType() {
		return eventType;
	}

	public Entry getEntry() {
		return entry;
	}

	public Map<?, ?> getParams() {
		return params;
	}

	public Date getDate() {
		return date;
	}
}

package cn.majingjing.tzx.event;

import java.util.ArrayList;

public class EntryEventDispatcher {

	private static EntryEventDispatcher instance = new EntryEventDispatcher();
	private ArrayList<EntryListener> listeners = new ArrayList<EntryListener>();

	public static EntryEventDispatcher getInstance() {
		return instance;
	}

	private EntryEventDispatcher() {

		String[] observers = PropertyMgr.getProperty("observers").split(",");
		for (String s : observers) {

			System.out.println(s);
			try {
				this.addListener((EntryListener) (Class.forName(s).newInstance()));
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}

	}

	public synchronized void addListener(EntryListener listener) {
		System.out.println(":" + listener);
		if (listener == null) {
			System.out.println(":" + listener);
			throw new NullPointerException();
		} else {
			listeners.add(listener);
			return;
		}
	}

	public synchronized void removeListener(EntryListener listener) {
		listeners.remove(listener);
	}

	public void dispatchEvent(EntryEvent event) {
		// System.out.println("msgDispatchEvent");
		int eventType = event.getEventType();
		long t1 = System.currentTimeMillis();
		System.out.println("kaishi=" + t1);
		for (int i = 0; i < listeners.size(); i++) {
			try {
				EntryListener listener = (EntryListener) listeners.get(i);
				String name = listener.getClass().getName();
				name = name.substring(name.lastIndexOf('.') + 1);

				switch (eventType) {
				case EntryEvent.ENTRY_ADDED:
					listener.entryAdded(event);
					break;

				case EntryEvent.ENTRY_DELETED:
					listener.entryDeleted(event);
					break;

				case EntryEvent.ENTRY_MODIFIED:
					listener.entryModified(event);
					break;

				}

			} catch (Exception e) {
				// logger.error(e);
			}

		}

		System.out.println("cost time=" + (System.currentTimeMillis() - t1));

		// Profiler.end("msgDispatchEvent");
	}
}

package cn.majingjing.tzx.event.manager;

import cn.majingjing.tzx.event.EntryEvent;
import cn.majingjing.tzx.event.EntryListener;

public class IndexManager implements EntryListener {

	@Override
	public void entryAdded(EntryEvent entryevent) {
		System.out.println("IndexManager add");

	}

	@Override
	public void entryDeleted(EntryEvent entryevent) {
		System.out.println("IndexManager del");

	}

	@Override
	public void entryModified(EntryEvent entryevent) {
		System.out.println("IndexManager modify");
	}

}

package cn.majingjing.tzx.event.manager;

import cn.majingjing.tzx.event.EntryEvent;
import cn.majingjing.tzx.event.EntryListener;

public class EmailManager implements EntryListener {

	@Override
	public void entryAdded(EntryEvent entryevent) {

		System.out.println("EmailManager add");

	}

	@Override
	public void entryDeleted(EntryEvent entryevent) {

		System.out.println("EmailManager del");
	}

	@Override
	public void entryModified(EntryEvent entryevent) {

		System.out.println("EmailManager modify");

	}

}

package cn.majingjing.tzx.event;

import java.io.IOException;
import java.util.Properties;

public class PropertyMgr {
	private static Properties props = new Properties();
	
	static {
		try {
			props.load(PropertyMgr.class.getClassLoader().getResourceAsStream("cn/majingjing/tzx/event/config.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String getProperty(String key) {
		return props.getProperty(key);
	}
}

配置文件 config.properties

observers=cn.majingjing.tzx.event.manager.IndexManager,cn.majingjing.tzx.event.manager.ScoreManager,cn.majingjing.tzx.event.manager.EmailManager

单元测试代码

package cn.majingjing.tzx;

import cn.majingjing.tzx.event.Entry;
import cn.majingjing.tzx.event.manager.EntryManager;

public class Test {

	public static void main(String[] args) {

		EntryManager eventManager = new EntryManager();
		Entry entry = new Entry();
		entry.setId(1);
		entry.setName("test");
		eventManager.addEntry(entry);
		eventManager.modifyEntry(entry);
		eventManager.deleteEntry(entry);

	}

}

源代码: Java观察者模式(Java事件监听)