Add: Event interface and implement it in DisconnectEvent, update EventBus to only allow Event type

This commit is contained in:
Lars Simon Winzer
2026-03-12 19:16:59 +01:00
parent 54588276d1
commit 7b32fe1147
3 changed files with 6 additions and 3 deletions
@@ -1,3 +1,3 @@
package ch.unibas.dmi.dbis.cs108.casono.server.network;
public record DisconnectEvent(SessionId sessionId) {}
public record DisconnectEvent(SessionId sessionId) implements Event {}
@@ -0,0 +1,3 @@
package ch.unibas.dmi.dbis.cs108.casono.server.network;
interface Event {}
@@ -9,12 +9,12 @@ import java.util.function.Consumer;
public class EventBus {
private final Map<Class<?>, List<Consumer<Object>>> handlers = new ConcurrentHashMap<>();
public <T> void subscribe(Class<T> eventType, Consumer<T> handler) {
public <T extends Event> void subscribe(Class<T> eventType, Consumer<T> handler) {
handlers.computeIfAbsent(eventType, k -> new CopyOnWriteArrayList<>())
.add((Consumer<Object>) handler);
}
public <T> void publish(T event) {
public <T extends Event> void publish(T event) {
List<Consumer<Object>> subscribers = handlers.get(event.getClass());
if (subscribers != null) {
subscribers.forEach(h -> h.accept(event));