Sunday, April 10, 2011

Very simple EventBus/PubSub implementation (Java)

While investigating and learning usage of CQRS parrtern I've found that there is no any simple event bus implementation for Java (exept this one, but it do not had sources).

So I've used idea of "Java Programming Tip: Building Your Own Event Bus" blog post, and made my own implementation.

It allows very-very simple and not optimized way of publishing/subscribing on events with consentation on simplicity.

Idea is very simple: Lets assume that "event handler" is any object that can recieve some object ("event"). So while adding some handler as "subscriber" we need to check all public methods (marked with "@EventHandler" annotation) and add them as subscribers to any object with same type as they parameter.

With this concept we can do something like this:

public class TestHandler {  

    @EventHandler
    public void handleString(String event) {
       ...
    }
}
...
EventDispatcher disp = new EventDispatcher();
TestHandler handler = new TestHandler();        
disp.addHandler(handler);
disp.publish("Hello");

Notice that I've used String as a event type. Actually any class could be used for it. For example:
public class CustomEvent {
  private String data;
  public CustomEvent(String data) {
    super();
    this.data = data;
  }
  public String getData() {
    return data;
  }
}

public class TestHandler {
  @EventHandler
  public void handleCustom(CustomEvent event) {
    // we can use event.getData();
  }
}
...
EventDispatcher disp = new EventDispatcher();
TestHandler handler = new TestHandler();  
disp.addHandler(handler);
disp.publish(new CustomEvent("something happen));


This implementation allows to create very simple to use/read code that need pub/subs.

Source code is available at GitHub repository, feel free to fork :)

No comments: