Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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;
@RunWith(MockitoJUnitRunner.class)
public class TestInterfaceDrivenEvent {
private SystemEventBus eventBus = new SystemEventBus();
@Spy
private MessageReceivedEventConsumer listener = new MessageReceivedEventConsumer();
@Before
public void registerListener() {
eventBus.registerListener(MessageRecievedEvent.class, listener);
}
@Test
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));
verify(listener).messageRecieved(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);
@Override
public void messageRecieved(Message msg) {
LOG.info("messageRecieved(), msg: {}", msg);
}
}
public class MessageRecievedEvent implements SystemEvent<MessageRecievedEventListener> {
private final Message msg;
public MessageRecievedEvent(Message msg) {
this.msg = msg;
}
@Override
public void notify(MessageRecievedEventListener listener) {
listener.messageRecieved(msg);
}
}
public interface MessageRecievedEventListener {
public void messageRecieved(Message msg);
}
public interface SystemEvent<L> {
public void notify(L listener);
}
import java.util.Collection;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
public class SystemEventBus {
// ReentrantReadWriteLock could be used if synchronization has proven to be a bottleneck
@SuppressWarnings("rawtypes")
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);
}
@SuppressWarnings("unchecked")
public <L> void fireEvent(SystemEvent<L> event) {
Collection<L> eventListeners = (Collection<L>) eventBusListeners.get(event.getClass());
for (L listener : eventListeners) {
event.notify(listener);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment