Wednesday, December 30, 2009

Publish-Subscribe Event Driven Programming

Publish-Subscribe messaging consists of loosely coupled system of topic/channel, publisher (provider), and subscriber (consumer).

Event Driven Programming allows the an objects to notify (i.e. publish an event) to observers.

Java programming model has long used the Observer/Listener pattern approach, and also Whiteboard pattern in OSGi environments.

However, there is no easy way and/or standardized convention to implement this.

Implementing the Observer pattern requires an object to extend Observable, which is "not POJO". Having listeners also clutter the class and there are a lot of boilerplate code to add:

private List<ClickListener> clickListeners = new ArrayList<ClickListener>();
private List<TouchListener> touchListeners = new ArrayList<TouchListener>();
public boolean addClickListener(ClickListener clickListener);
public boolean addTouchListener(TouchListener touchListener);
public List<ClickListener> getClickListeners();
public List<TouchListener> getTouchListeners();
public boolean removeClickListener(ClickListener clickListener);
public boolean removeTouchListener(TouchListener touchListener);
private void fireClick(ClickEvent clickEvent);
private void fireTouch(TouchEvent touchEvent);

See what I mean? That's only for two listeners, and those are only method signatures.

The implementation are probably trivial, but it's very boring to repeat these over and over again in most of your classes.

And what if the implementation isn't perfect? Will you change all those?

Over the next few posts, I'll explore the potential solutions.

No comments:

Post a Comment