Is there a recommended way to use the Observer pattern in MVP using GWT?

Program Structure

This is how I did it. The Eventbus lets presenters (extending the abstract class Subscriber) subscribe to events belonging to different modules in my app. Each module corresponds to a component in my system, and each module has an event type, a presenter, a handler, a view and a model.

A presenter subscribing to all the events of type CONSOLE will receive all the events triggered from that module. For a more fine-grained approach you can always let presenters subscribe to specific events, such as NewLineAddedEvent or something like that, but for me I found that dealing with it on a module level was good enough.

If you want you could make the call to the presenter’s rescue methods asynchronous, but so far I’ve found little need to do so myself. I suppose it depends on what your exact needs are. This is my EventBus:

public class EventBus implements EventHandler 
{
    private final static EventBus INSTANCE = new EventBus();
    private HashMap<Module, ArrayList<Subscriber>> subscribers;

    private EventBus()  
    { 
      subscribers = new HashMap<Module, ArrayList<Subscriber>>(); 
    }

    public static EventBus get() { return INSTANCE; }

    public void fire(ScEvent event)
    {
        if (subscribers.containsKey(event.getKey()))
            for (Subscriber s : subscribers.get(event.getKey()))
                s.rescue(event);
    }

    public void subscribe(Subscriber subscriber, Module[] keys)
    {
        for (Module m : keys)
            subscribe(subscriber, m);
    }

    public void subscribe(Subscriber subscriber, Module key)
    {
        if (subscribers.containsKey(key))
            subscribers.get(key).add(subscriber);
        else
        {
            ArrayList<Subscriber> subs = new ArrayList<Subscriber>();
            subs.add(subscriber);
            subscribers.put(key, subs);
        }
    }

    public void unsubscribe(Subscriber subscriber, Module key)
    {
        if (subscribers.containsKey(key))
            subscribers.get(key).remove(subscriber);
    }

}

Handlers are attached to components, and are responsible for transforming native GWT events into events specialised for my system. The handler below deals with ClickEvents simply by wrapping them in a customised event and firing them on the EventBus for the subscribers to deal with. In some cases it makes sense for the handlers to perform extra checks before firing the event, or sometimes even before deciding weather or not to send the event. The action in the handler is given when the handler is added to the graphical component.

public class AppHandler extends ScHandler
{
    public AppHandler(Action action) { super(action); }

    @Override
    public void onClick(ClickEvent event) 
    { 
         EventBus.get().fire(new AppEvent(action)); 
    }

Action is an enumeration expressing possible ways of data manipulation in my system. Each event is initialised with an Action. The action is used by presenters to determine how to update their view. An event with the action ADD might make a presenter add a new button to a menu, or a new row to a grid.

public enum Action 
{
    ADD,
    REMOVE,
    OPEN,
    CLOSE,
    SAVE,
    DISPLAY,
    UPDATE
}

The event that’s get fired by the handler looks a bit like this. Notice how the event defines an interface for it’s consumers, which will assure that you don’t forget to implement the correct rescue methods.

public class AppEvent extends ScEvent {

    public interface AppEventConsumer 
    {
        void rescue(AppEvent e);
    }

    private static final Module KEY = Module.APP;
    private Action action;

    public AppEvent(Action action) { this.action = action; }

The presenter subscribes to events belonging to diffrent modules, and then rescues them when they’re fired. I also let each presenter define an interface for it’s view, which means that the presenter won’t ever have to know anything about the actual graphcal components.

public class AppPresenter extends Subscriber implements AppEventConsumer, 
                                                        ConsoleEventConsumer
{
    public interface Display 
    {
        public void openDrawer(String text);
        public void closeDrawer();
    }

    private Display display;

    public AppPresenter(Display display)
    {
        this.display = display;
        EventBus.get().subscribe(this, new Module[]{Module.APP, Module.CONSOLE});
    }

    @Override
    public void rescue(ScEvent e) 
    {
        if (e instanceof AppEvent)
            rescue((AppEvent) e);
        else if (e instanceof ConsoleEvent)
            rescue((ConsoleEvent) e);
    }
}

Each view is given an instance of a HandlerFactory that is responsible for creating the correct type of handler for each view. Each factory is instantiated with a Module, that it uses to create handlers of the correct type.

public ScHandler create(Action action)
{
  switch (module)
  {
    case CONSOLE :
      return new ConsoleHandler(action);

The view is now free to add handlers of different kind to it’s components without having to know about the exact implementation details. In this example, all the view needs to know is that the addButton button should be linked to some behaviour corresponding to the action ADD. What this behaviour is will be decided by the presenters that catch the event.

public class AppView implements Display

   public AppView(HandlerFactory factory)
   {
       ToolStripButton addButton = new ToolStripButton();
       addButton.addClickHandler(factory.create(Action.ADD));
       /* More interfacy stuff */  
   }

   public void openDrawer(String text) { /*Some implementation*/ }
   public void closeDrawer() {  /*Some implementation*/ }

Example

Consider a simplified Eclipse where you have a class hierarchy to the left, a text area for code on the right, and a menu bar on top. These three would be three different views with three different presenters and therefore they’d make up three different modules. Now, it’s entirely possible that the text area will need to change in accordance to changes in the class hierarchy, and therefore it makes sense for the text area presenter to subscribe not only to events being fired from within the text area, but also to events being fired from the class hierarchy. I can imagine something like this (for each module there will be a set of classes – one handler, one event type, one presenter, one model and one view):

public enum Module 
{
   MENU,
   TEXT_AREA,
   CLASS_HIERARCHY
}

Now consider we want our views to update properly upon deletion of a class file from the hierarchy view. This should result in the following changes to the gui:

  1. The class file should be removed from the class hierarchy
  2. If the class file is opened, and therefore visible in the text area, it should be closed.

Two presenters, the one controlling the tree view and the one controlling the text view, would both subscribe to events fired from the CLASS_HIERARCHY module. If the action of the event is REMOVE, both preseneters could take the appropriate action, as described above. The presenter controlling the hierarchy would presumably also send a message to the server, making sure that the deleted file was actually deleted. This set-up allows modules to react to events in other modules simply by listening to events fired from the event bus. There is very little coupling going on, and swapping out views, presenters or handlers is completely painless.

Leave a Comment