Added event system

+ Event interface for defining event objects
+ EventHandler interface for defining event handlers
+ EventBus singleton class for managing event handlers and dispatching
events
This commit is contained in:
Kai S. K. Engelbart 2019-12-04 18:50:06 +01:00
parent 378a83638a
commit 3c7f95f869
3 changed files with 73 additions and 0 deletions

View File

@ -0,0 +1,16 @@
package envoy.client.event;
/**
* Project: <strong>envoy-clientChess</strong><br>
* File: <strong>Event.javaEvent.java</strong><br>
* Created: <strong>04.12.2019</strong><br>
*
* @author Kai S. K. Engelbart
*/
public interface Event<T> {
/**
* @return the data associated with this event
*/
T get();
}

View File

@ -0,0 +1,32 @@
package envoy.client.event;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Project: <strong>envoy-clientChess</strong><br>
* File: <strong>EventBus.javaEvent.java</strong><br>
* Created: <strong>04.12.2019</strong><br>
*
* @author Kai S. K. Engelbart
*/
public class EventBus {
private static EventBus eventBus;
private List<EventHandler> handlers = new ArrayList<>();
private EventBus() {}
public EventBus getInstance() {
if (eventBus == null) eventBus = new EventBus();
return eventBus;
}
public void register(EventHandler... handlers) { this.handlers.addAll(Arrays.asList(handlers)); }
public void dispatch(Event<?> event) { handlers.stream().filter(h -> h.supports().contains(event.getClass())).forEach(h -> h.handle(event)); }
public List<EventHandler> getHandlers() { return handlers; }
}

View File

@ -0,0 +1,25 @@
package envoy.client.event;
import java.util.Set;
/**
* Project: <strong>envoy-clientChess</strong><br>
* File: <strong>EventHandler.javaEvent.java</strong><br>
* Created: <strong>04.12.2019</strong><br>
*
* @author Kai S. K. Engelbart
*/
public interface EventHandler {
/**
* Consumes an event dispatched by the event bus.
*
* @param event The event dispatched by the event bus, only of supported type
*/
void handle(Event<?> event);
/**
* @return A set of classes this class is supposed to handle in events
*/
Set<Class<? extends Event<?>>> supports();
}