事件驱动模型的简单Java实现
事件驱动模型的原理不再赘述,Swing是不错的实现。别人也有不错的博文来说明原理。
本文的目的是提供一种简单的,可供参考的简短代码,用来帮助理解该模型。
Project Navigator
Event
事件通用接口:
- package org.joshua.event.events;
- public interface Event {
- }
Click事件:
- package org.joshua.event.events;
- public class ClickEvent implements Event {
- }
Double click事件:
- package org.joshua.event.events;
- public class DblClickEvent implements Event {
- }
Listener
事件监听器通用接口:
- package org.joshua.event.listener;
- import org.joshua.event.events.Event;
- public interface EventListener<T extends Event> {
- public void handleEvent(T event);
- }
Click事件监听器:
- package org.joshua.event.listener;
- import org.joshua.event.events.ClickEvent;
- public interface ClickEventHandler extends EventListener<ClickEvent> {
- }
Double Click事件监听器:
- package org.joshua.event.listener;
- import org.joshua.event.events.DblClickEvent;
- public interface DblClickEventHandler extends EventListener<DblClickEvent> {
- }
Event Source
事件源通用接口:
- package org.joshua.event.source;
- import org.joshua.event.events.Event;
- import org.joshua.event.listener.EventListener;
- public interface EventSource {
- void addEventListener(EventListener<? extends Event> listener);
- void removeEventListener(EventListener<? extends Event> listener);
- void notifyListeners(Event event);
- }
模拟的按钮控件:
- package org.joshua.event.source;
- import java.util.LinkedList;
- import java.util.List;
- import org.joshua.event.events.Event;
- import org.joshua.event.listener.EventListener;
- public class Button implements EventSource {
- protected List<EventListener<? extends Event>> listeners = new LinkedList<EventListener<? extends Event>>();
- @Override
- public void addEventListener(EventListener<? extends Event> listener) {
- listeners.add(listener);
- }
- @Override
- public void removeEventListener(EventListener<? extends Event> listener) {
- listeners.remove(listener);
- }
- @Override
- public void notifyListeners(Event event) {
- for (EventListener listener : listeners) {
- try {
- listener.handleEvent(event);
- } catch (ClassCastException e) {
- }
- }
- }
- }
Client
- package org.joshua.event;
- import org.joshua.event.events.ClickEvent;
- import org.joshua.event.events.DblClickEvent;
- import org.joshua.event.events.Event;
- import org.joshua.event.listener.ClickEventHandler;
- import org.joshua.event.listener.DblClickEventHandler;
- import org.joshua.event.source.Button;
- import org.junit.Before;
- import org.junit.Test;
- public class Client {
- private Event currentEvent;
- private Button button;
- @Before
- public void initComponent() {
- button = new Button();
- button.addEventListener(new ClickEventHandler() {
- @Override
- public void handleEvent(ClickEvent event) {
- System.out.println("Button was clicked!");
- }
- });
- button.addEventListener(new DblClickEventHandler() {
- @Override
- public void handleEvent(DblClickEvent event) {
- System.out.println("Button was double clicked!");
- }
- });
- }
- @Test
- public void testCommonEvents() {
- currentEvent = new ClickEvent();
- button.notifyListeners(currentEvent);
- currentEvent = new DblClickEvent();
- button.notifyListeners(currentEvent);
- }
- }
Button类中的notifyListener方法实现起来虽方便,利用了一把异常机制,但着实不推荐大家在项目中这样做。且不说性能问题,Listener的handleEvent方法里所有抛出的ClassCastException都需要重新包装。当然,我们可以使用annotation、限定类名等方式相对优雅地解决event和对应listener的mapping问题。
多线程事件处理机制
思路是用队列暂存事件,然后若干个事件分发器将事件分发给指定数量的事件处理线程处理。
- package com.joshua.test.event;
- import java.util.concurrent.BlockingQueue;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.LinkedBlockingQueue;
- import com.joshua.test.event.event.Event;
- import com.joshua.test.event.event.EventType;
- import com.joshua.test.event.handler.CreateEventHandler;
- public class EventManager {
- private static final int EVENT_QUEUE_LENGTH = 1000;
- private static final int DISPATCHER_NUM = 2;
- private static final int EVENT_HANDLER_NUM = 10;
- public BlockingQueue<Event> eventQueue = new LinkedBlockingQueue<Event>(EVENT_QUEUE_LENGTH);
- private ExecutorService eventHandlerPool;
- protected EventDispatcher createDispatcher() {
- EventDispatcher dispatcher = new EventDispatcher(this.eventQueue, this.eventHandlerPool);
- dispatcher.register(EventType.CREATE, CreateEventHandler.class);
- return dispatcher;
- }
- public void init() {
- eventHandlerPool = Executors.newFixedThreadPool(EVENT_HANDLER_NUM);
- }
- public void start() {
- for (int i = 0; i < DISPATCHER_NUM; i++) {
- createDispatcher().start();
- }
- }
- public void notify(Event event) {
- try {
- eventQueue.put(event);
- } catch (InterruptedException e) {
- }
- }
- }
- package com.joshua.test.event;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.concurrent.BlockingQueue;
- import java.util.concurrent.ExecutorService;
- import com.joshua.test.event.event.Event;
- import com.joshua.test.event.event.EventType;
- import com.joshua.test.event.handler.EventHandler;
- @SuppressWarnings("rawtypes")
- public class EventDispatcher {
- private final BlockingQueue<Event> eventQueue;
- private final ExecutorService eventHandlerPool;
- protected final Map<EventType, Class<? extends EventHandler>> eventDispatchers = new HashMap<EventType, Class<? extends EventHandler>>();
- private Thread eventHandlingThread;
- private volatile boolean stopped = false;
- public EventDispatcher(BlockingQueue<Event> eventQueue, ExecutorService eventHandlerPool) {
- this.eventQueue = eventQueue;
- this.eventHandlerPool = eventHandlerPool;
- System.out.println("Event dispatcher starting...");
- }
- Runnable createThread() {
- return new Runnable() {
- @Override
- public void run() {
- while (!stopped && !Thread.currentThread().isInterrupted()) {
- Event event;
- try {
- event = eventQueue.take();
- } catch (InterruptedException ie) {
- if (!stopped) {
- System.out.println("Dispatcher thread interrupted");
- ie.printStackTrace();
- }
- return;
- }
- if (event != null) {
- dispatch(event);
- }
- }
- }
- };
- }
- @SuppressWarnings("unchecked")
- protected void dispatch(Event event) {
- EventType type = event.getType();
- try {
- Class<? extends EventHandler> handlerClazz = eventDispatchers
- .get(type);
- if (handlerClazz != null) {
- EventHandler handler = handlerClazz.newInstance();
- handler.setEvent(event);
- eventHandlerPool.submit(handler);
- } else {
- throw new Exception("No handler for registered for " + type);
- }
- } catch (Throwable t) {
- System.err.println("Error in dispatcher thread");
- t.printStackTrace();
- System.exit(-1);
- }
- }
- public void register(EventType eventType,
- Class<? extends EventHandler> handler) {
- Class<? extends EventHandler> registeredHandler = eventDispatchers
- .get(eventType);
- System.out.println("Registering " + eventType + " for "
- + handler);
- if (registeredHandler == null) {
- eventDispatchers.put(eventType, handler);
- }
- }
- public void start() {
- eventHandlingThread = new Thread(createThread());
- eventHandlingThread.setName("AsyncDispatcher event handler");
- eventHandlingThread.start();
- System.out.println("Event dispatcher started!");
- }
- public void stop() {
- stopped = true;
- if (eventHandlingThread != null) {
- eventHandlingThread.interrupt();
- try {
- eventHandlingThread.join();
- } catch (InterruptedException ie) {
- System.out.println("Interrupted Exception while stopping");
- ie.printStackTrace();
- }
- }
- }
- }
转自 http://joshuasabrina.iteye.com/blog/1812722