事件驅動模型的簡單Java實現
阿新 • • 發佈:2018-11-05
事件驅動模型的原理不再贅述,Swing是不錯的實現。別人也有不錯的博文來說明原理。
本文的目的是提供一種簡單的,可供參考的簡短程式碼,用來幫助理解該模型。
Project Navigator
Event
事件通用介面:
Java程式碼- package org.joshua.event.events;
- public interface Event {
- }
Click事件:
Java程式碼- package org.joshua.event.events;
- public class ClickEvent implements Event {
- }
Double click事件:
Java程式碼- package org.joshua.event.events;
- public class DblClickEvent implements Event {
- }
Listener
事件監聽器通用介面:
Java程式碼- package org.joshua.event.listener;
- import org.joshua.event.events.Event;
- public interface EventListener<T extends Event> {
- public void handleEvent(T event);
- }
Click事件監聽器:
Java程式碼- package org.joshua.event.listener;
- import org.joshua.event.events.ClickEvent;
- public interface ClickEventHandler extends EventListener<ClickEvent> {
- }
Double Click事件監聽器:
Java程式碼- package org.joshua.event.listener;
- import org.joshua.event.events.DblClickEvent;
- public interface DblClickEventHandler extends EventListener<DblClickEvent> {
- }
Event Source
事件源通用介面:
Java程式碼- 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);
- }
模擬的按鈕控制元件:
Java程式碼- 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
Java程式碼- 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問題。
多執行緒事件處理機制
思路是用佇列暫存事件,然後若干個事件分發器將事件分發給指定數量的事件處理執行緒處理。
Java程式碼- 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) {
- }
- }
- }
Java程式碼
- 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();
- }
- }
- }
- }