event bus implementation that uses dynamic method invocation

pull/4/head
Zlatin Balevsky 2018-07-20 04:03:04 +01:00
parent fe405d5faf
commit 95071deb0a
2 changed files with 56 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package com.muwire.core
import java.util.concurrent.CopyOnWriteArrayList
import com.muwire.core.files.FileSharedEvent
class EventBus {
private Map handlers = new HashMap()
void publish(Event e) {
def currentHandlers
final def clazz = e.getClass()
synchronized(handlers) {
currentHandlers = handlers.getOrDefault(clazz, [])
}
currentHandlers.each {
it."on${clazz.getSimpleName()}"(e)
}
}
synchronized void register(Class<? extends Event> eventType, def handler) {
def currentHandlers = handlers.get(eventType)
if (currentHandlers == null) {
currentHandlers = new CopyOnWriteArrayList()
handlers.put(eventType, currentHandlers)
}
currentHandlers.add handler
}
}

View File

@ -0,0 +1,26 @@
package com.muwire.core
import org.junit.Test
class EventBusTest {
class FakeEvent extends Event {}
class FakeEventHandler {
def onFakeEvent(FakeEvent e) {
assert e == fakeEvent
}
}
FakeEvent fakeEvent = new FakeEvent()
EventBus bus = new EventBus()
def handler = new FakeEventHandler()
@Test
void testDynamicEvent() {
bus.register(FakeEvent.class, handler)
bus.publish(fakeEvent)
}
}