package dev.kske.chess.event;
import java.util.ArrayList;
import java.util.List;
/**
* Dispatches {@link Event}s to various {@link Subscriber}s.
*
* Project: Chess
* File: EventBus.java
* Created: 7 Aug 2019
*
* @since Chess v0.4-alpha
* @author Kai S. K. Engelbart
*/
public class EventBus {
private List subscribers;
private static EventBus instance;
/**
* @return a singleton instance of {@link EventBus}
*/
public static EventBus getInstance() {
if (instance == null)
instance = new EventBus();
return instance;
}
private EventBus() {
subscribers = new ArrayList<>();
}
/**
* Registers a subscriber to which future events will be dispatched.
*
* @param subscribable the subscriber to register
*/
public void register(Subscriber subscribable) {
subscribers.add(subscribable);
}
/**
* Dispatches an event to all {@Subscriber}s registered at this event bus.
*
* @param event the event to dispatch
*/
public void dispatch(Event> event) {
subscribers.stream()
.filter(e -> e.supports().contains(event.getClass()))
.forEach(e -> e.handle(event));
}
/**
* @return a list of all registered subscribers
*/
public List getSubscribers() { return subscribers; }
}