事件驱动模型基本结构
事件驱驱动架构由三个基本组件构成,事件、事件处理器、事件循环。事件产生后发送给事件循环,事件循环将每个事件分派给个各个事件处理器。事件A由处理器A处理,事件B将被处理器B处理。
事件
事件驱动架构的核心是事件。事件至少包含两个必须的属性:类型和数据。事件的类型确定了由哪个事件处理器来处理事件及事件相关的数据。因此我们可以将事件对象看作是数据的容器。Java中一个简单的事件对象模型如下。
public static class Event {
public char type;
public String data;
public Event(char type, String data) {
this.type = type;
this.data = data;
}
}
事件处理器
处理器用来处理具体的事件。常用的操作包括过滤、转换与事件关联的数据。
public static void printEventA(Event e) {
System.out.println(e.data);
}
示例代码中的处理器用来处理事件A,并将数据打印。
public static void printEventB(Event e) {
System.out.println(e.data.toUpperCase());
}
第2个例子中,处理器将数据转换为大写。
事件循环
当事件循环接收到事件后,会将事件派发给每个事件各自的处理器。
public static void main(String[] args) {
Queue<Event> events = new LinkedList<Event>();
events.add(new Event('A', "Hello"));
events.add(new Event('B', "event-driven"));
events.add(new Event('A', "world!"));
Event e;
while (!events.isEmpty()) {
e = events.remove();
if (e.type == 'A')
printEventA(e);
if (e.type == 'B')
printEventB(e);
}
}
在初始化事件循环前,我们创建了一个事件队列来调度不同的事件。因此我们可以看到相应的输出结果。
在事件循环中,每个事件根据了相应的类型来进行处理,直到没有事件为止。
完整例子
import java.util.LinkedList;
import java.util.Queue;
public class EventMachine {
// Event definition
public static class Event {
public char type;
public String data;
public Event(char type, String data) {
this.type = type;
this.data = data;
}
}
// Event handler A
public static void printEventA(Event e) {
System.out.println(e.data);
}
// Event handler B
public static void printEventB(Event e) {
System.out.println(e.data.toUpperCase());
}
public static void main(String[] args) {
Queue<Event> events = new LinkedList<Event>();
events.add(new Event('A', "Hello"));
events.add(new Event('B', "event-driven"));
events.add(new Event('A', "world!"));
// Event loop
Event e;
while (!events.isEmpty()) {
e = events.remove();
if (e.type == 'A')
printEventA(e);
if (e.type == 'B')
printEventB(e);
}
}
}
结语
本文介绍了事件驱动模型基本的组件,并通过Java语言进行了简单的实现。下一篇将通过Java语言并结合一些设计模式来实现一个简单的事件驱动框架。Java实现事件驱动模型(一)
原文地址
http://www.giocc.com/fundamental-components-of-an-event-driven-architecture.html