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:
parent
3d4b472afb
commit
c70416df28
16
src/main/java/envoy/client/event/Event.java
Normal file
16
src/main/java/envoy/client/event/Event.java
Normal 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();
|
||||
}
|
32
src/main/java/envoy/client/event/EventBus.java
Normal file
32
src/main/java/envoy/client/event/EventBus.java
Normal 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; }
|
||||
}
|
25
src/main/java/envoy/client/event/EventHandler.java
Normal file
25
src/main/java/envoy/client/event/EventHandler.java
Normal 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();
|
||||
}
|
Reference in New Issue
Block a user