This repository has been archived on 2021-12-05. You can view files and clone it, but cannot push or open issues or pull requests.
envoy/src/main/java/envoy/client/event/EventBus.java

82 lines
2.6 KiB
Java

package envoy.client.event;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class handles events by allowing {@link EventHandler} object to register
* themselves and then be notified about certain events dispatched by the event
* bus.<br>
* <br>
* The event bus is a singleton and can be used across the entire application to
* guarantee the propagation of events.<br>
*
* Project: <strong>envoy-client</strong><br>
* File: <strong>EventBus.java</strong><br>
* Created: <strong>04.12.2019</strong><br>
*
* @author Kai S. K. Engelbart
* @since Envoy v0.2-alpha
*/
public class EventBus {
/**
* Contains all {@link EventHandler} instances registered at this
* {@link EventBus} as values mapped to by their supported {@link Event}
* classes.
*/
private Map<Class<? extends Event<?>>, List<EventHandler>> handlers = new HashMap<>();
/**
* The singleton instance of this {@link EventBus} that is used across the
* entire application.
*/
private static EventBus eventBus = new EventBus();
/**
* This constructor is not accessible from outside this class because a
* singleton instance of it is provided by the {@link EventBus#getInstance()}
* method.
*/
private EventBus() {}
/**
* @return the singleton instance of the {@link EventBus}
* @since Envoy v0.2-alpha
*/
public static EventBus getInstance() { return eventBus; }
/**
* Registers an {@link EventHandler} to be notified when a
* {@link Event} of a certain type is dispatched.
*
* @param eventClass the class which the {@link EventHandler} is subscribed to
* @param handler the {@link EventHandler} to register
* @since Envoy v0.2-alpha
*/
public void register(Class<? extends Event<?>> eventClass, EventHandler handler) {
if (!handlers.containsKey(eventClass)) handlers.put(eventClass, new ArrayList<>());
handlers.get(eventClass).add(handler);
}
/**
* Dispatches a {@link Event} to every {@link EventHandler} subscribed to it.
*
* @param event the {@link Event} to dispatch
* @since Envoy v0.2-alpha
*/
public void dispatch(Event<?> event) {
handlers.keySet().stream().filter(event.getClass()::isAssignableFrom).map(handlers::get).flatMap(List::stream).forEach(h -> h.handle(event));
}
/**
* @return a map of all {@link EventHandler} instances currently registered at
* this {@link EventBus} with the {@link Event} classes they are
* subscribed to as keys
* @since Envoy v0.2-alpha
*/
public Map<Class<? extends Event<?>>, List<EventHandler>> getHandlers() { return handlers; }
}