Created
July 17, 2016 20:45
-
-
Save char/d858552c19c129d909d3d0d25a511003 to your computer and use it in GitHub Desktop.
Event Bus in 58 lines of Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package site.hackery.photon; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.function.BooleanSupplier; | |
import java.util.function.Consumer; | |
import static java.util.Arrays.asList; | |
public class EventBus { | |
public interface Handler<T> { | |
void handle(T event); | |
} | |
public interface Registrator<T> { | |
void to(Handler<T> handler); | |
default void when(BooleanSupplier condition, Handler<T> handler) { | |
to(event -> { | |
if (condition.getAsBoolean()) { | |
handler.handle(event); | |
} | |
}); | |
} | |
} | |
private static Map<Class<?>, List<Handler>> map = new HashMap<>(); | |
public static <T> Registrator<T> register(Class<T> cls) { | |
return handler -> { | |
map.putIfAbsent(cls, new ArrayList<>()); | |
map.get(cls).add(handler); | |
}; | |
} | |
public static <T> void post(T event) { | |
forAllSuperclasses(event.getClass()).invoke(cls -> map.getOrDefault(cls, new ArrayList<>()).forEach(handler -> handler.handle(event))); | |
} | |
private interface OnEachClass { | |
void invoke(Consumer<Class<?>> cls); | |
} | |
private static OnEachClass forAllSuperclasses(Class<?> clazz) { | |
return action -> { | |
Class<?> superCls = clazz; | |
while (superCls != Object.class) { | |
action.accept(superCls); | |
asList(superCls.getInterfaces()).forEach(interfaceCls -> { | |
action.accept(interfaceCls); | |
}); | |
superCls = superCls.getSuperclass(); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment