Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2015 14:26
Show Gist options
  • Save marlly/01075cf4ccc40920f8f4 to your computer and use it in GitHub Desktop.
Save marlly/01075cf4ccc40920f8f4 to your computer and use it in GitHub Desktop.
Example of interface driven events
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
public class TestInterfaceDrivenEvent {
private SystemEventBus eventBus = new SystemEventBus();
private MessageReceivedEventConsumer listener = new MessageReceivedEventConsumer();
public void registerListener() {
eventBus.registerListener(MessageRecievedEvent.class, listener);
public void fireEvent() {
Message msg = new Message("marlly", "Interface vs annotation driven events", "Post about differences between those event architectures");
eventBus.fireEvent(new MessageRecievedEvent(msg));
public class Message {
private final String sender;
private final String subject;
private final String text;
public Message(String sender, String subject, String text) {
this.sender = sender;
this.subject = subject;
this.text = text;
public String getSender() {
return sender;
public String getSubject() {
return subject;
public String getText() {
return text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MessageReceivedEventConsumer implements MessageRecievedEventListener {
private static final Logger LOG = LoggerFactory.getLogger(MessageReceivedEventConsumer.class);
public void messageRecieved(Message msg) {"messageRecieved(), msg: {}", msg);
public class MessageRecievedEvent implements SystemEvent<MessageRecievedEventListener> {
private final Message msg;
public MessageRecievedEvent(Message msg) {
this.msg = msg;
public void notify(MessageRecievedEventListener listener) {
public interface MessageRecievedEventListener {
public void messageRecieved(Message msg);
public interface SystemEvent<L> {
public void notify(L listener);
import java.util.Collection;
public class SystemEventBus {
// ReentrantReadWriteLock could be used if synchronization has proven to be a bottleneck
private final Multimap<Class, Object> eventBusListeners = Multimaps.synchronizedMultimap(HashMultimap.<Class, Object> create());
public <L> void registerListener(Class<? extends SystemEvent<L>> eventClass, L listener) {
eventBusListeners.put(eventClass, listener);
public <L> void fireEvent(SystemEvent<L> event) {
Collection<L> eventListeners = (Collection<L>) eventBusListeners.get(event.getClass());
for (L listener : eventListeners) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment