Event driven architecture refactored.

1. Renamed Message to Event and Event to AbstractEvent
2. Generified Event and Handler
3. Updated EventDispatcher to make unsafe configuration impossible
4. Updated UML diagram accordingly
This commit is contained in:
Oleg
2016-03-08 00:56:08 -08:00
parent 35d6a54831
commit afb897300b
13 changed files with 115 additions and 131 deletions
@@ -23,15 +23,15 @@
package com.iluwatar.eda.framework;
/**
* A {@link Message} is an object with a specific type that is associated
* A {@link Event} is an object with a specific type that is associated
* to a specific {@link Handler}.
*/
public interface Message {
public interface Event {
/**
* Returns the message type as a {@link Class} object. In this example the message type is
* used to handle events by their type.
* @return the message type as a {@link Class}.
*/
Class<? extends Message> getType();
Class<? extends Event> getType();
}
@@ -22,19 +22,16 @@
*/
package com.iluwatar.eda.framework;
import com.iluwatar.eda.event.Event;
import java.util.HashMap;
import java.util.Map;
/**
* Handles the routing of {@link Event} messages to associated handlers.
* A {@link HashMap} is used to store the association between events and their respective handlers.
*
*/
public class EventDispatcher {
private Map<Class<? extends Event>, Handler<?>> handlers;
private Map<Class<? extends Event>, Handler<? extends Event>> handlers;
public EventDispatcher() {
handlers = new HashMap<>();
@@ -46,8 +43,8 @@ public class EventDispatcher {
* @param eventType The {@link Event} to be registered
* @param handler The {@link Handler} that will be handling the {@link Event}
*/
public void registerChannel(Class<? extends Event> eventType,
Handler<?> handler) {
public <E extends Event> void registerHandler(Class<E> eventType,
Handler<E> handler) {
handlers.put(eventType, handler);
}
@@ -56,8 +53,12 @@ public class EventDispatcher {
*
* @param event The {@link Event} to be dispatched
*/
public void onEvent(Event event) {
handlers.get(event.getClass()).onEvent(event);
@SuppressWarnings("unchecked")
public <E extends Event> void dispatch(E event) {
Handler<E> handler = (Handler<E>) handlers.get(event.getClass());
if (handler != null) {
handler.onEvent(event);
}
}
}
@@ -22,13 +22,11 @@
*/
package com.iluwatar.eda.framework;
import com.iluwatar.eda.event.Event;
/**
* This interface can be implemented to handle different types of messages.
* Every handler is responsible for a single of type message
*/
public interface Handler<E extends Message> {
public interface Handler<E extends Event> {
/**
* The onEvent method should implement and handle behavior related to the event.
@@ -36,5 +34,5 @@ public interface Handler<E extends Message> {
* a queue to be consumed by other sub systems.
* @param event the {@link Event} object to be handled.
*/
void onEvent(Event event);
void onEvent(E event);
}