60 lines
1.4 KiB
Java
60 lines
1.4 KiB
Java
package dev.kske.chess.event;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
/**
|
|
* Dispatches {@link Event}s to various {@link Subscriber}s.<br>
|
|
* <br>
|
|
* Project: <strong>Chess</strong><br>
|
|
* File: <strong>EventBus.java</strong><br>
|
|
* Created: <strong>7 Aug 2019</strong><br>
|
|
*
|
|
* @since Chess v0.4-alpha
|
|
* @author Kai S. K. Engelbart
|
|
*/
|
|
public class EventBus {
|
|
|
|
private List<Subscriber> 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<Subscriber> getSubscribers() { return subscribers; }
|
|
}
|