mirror of https://github.com/zlatinb/muwire
event bus implementation that uses dynamic method invocation
parent
fe405d5faf
commit
95071deb0a
|
@ -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
|
||||||
|
}
|
||||||
|
}
|
|
@ -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)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue