17

I am thinking about implementing a user interface according to the MVP pattern using GWT, but have doubts about how to proceed.

These are (some of) my goals:

  • the presenter knows nothing about the UI technology (i.e. uses nothing from com.google.*)
  • the view knows nothing about the presenter (not sure yet if I'd like it to be model-agnostic, yet)
  • the model knows nothing of the view or the presenter (...obviously)

I would place an interface between the view and the presenter and use the Observer pattern to decouple the two: the view generates events and the presenter gets notified.

What confuses me is that java.util.Observer and java.util.Observable are not supported in GWT. This suggests that what I'm doing is not the recommended way to do it, as far as GWT is concerned, which leads me to my questions: what is the recommended way to implement MVP using GWT, specifically with the above goals in mind? How would you do it?

1

3 Answers 3

33

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.

4
  • This is quite an elaborate approach and an extensive answer, thank you. Could you extend it a bit further by explaining what the role of Subscriber is? Also, what's the idea behind subscribing a presenter to modules? The way I'm thinking about it, a presenter is strongly related and localized to a specific view-model pair. Also, you use a single Action class to define all actions which can be triggered from any part of the UI: does it become messy when enough classes add their actions? Also, that means changes in any module will affect Action, which sounds a bit worrying... Commented May 14, 2010 at 13:20
  • No problem! Best of luck to you, and if you have any follow-up questions I'd be happy to help you.
    – Mia Clarke
    Commented May 18, 2010 at 13:09
  • where is the variable "action" in Apphandler.onClick declared or initialized? Bug? Commented Mar 7, 2013 at 15:11
  • This is not a bug, the code has simply been omitted for readability. The initialisation is done in the constructor of the superclass.
    – Mia Clarke
    Commented Mar 7, 2013 at 21:09
2

I achieved something on these lines for our project. I wanted a event-driven mechanism (think of PropertyChangeSupport and PropertyChangeListener of standard jdk lib) which were missing. I believe there is an extension module and decided to go ahead with my own. You can google it for propertychangesupport gwt and use it or go with my approach.

My approach involved logic centred around MessageHandler and GWTEvent. These serve the same purpose as that of PropertyChangeListener and PropertyChangeEvent respectively. I had to customize them for reasons explained later. My design involved a MessageExchange, MessageSender and MessageListener. The exchange acts as a broadcast service dispatching all events to all listeners. Each sender fires events that are listened by the Exchange and the exchange the fires the events again. Each listener listens to the exchange and can decide for themselves (to process or not to process) based on the event.

Unfortunately MessageHandlers in GWT suffer from a problem: "While a event is being consumed, no new handlers can be hooked". Reason given in the GWT form: The backing iterator holding the handlers cannot be concurrently modified by another thread. I had to rewrite custom implementation of the GWT classes. That is the basic idea.

I would've posted the code, but I am on my way to airport right now, will try to post the code as soon as I can make time.

Edit1:

Not yet able to get the actual code, got hold of some power-point slides I was working on for design documentation and created a blog entry.

Posting a link to my blog article: GXT-GWT App

Edit2:

Finally some code soup. Posting 1 Posting 2 Posting 3

4
  • Thank you for your answer. Could you compare your MessageExchange to Banang's EventBus? I'm not sure at the moment what you get by making all the listeners evaluate every event application-wide to see if it's something they should handle, which is how I understood the MessageExchange approach to work... Commented May 14, 2010 at 13:24
  • Quick answer; some call it potaatoe, some call it potaytoe! I really did not try to achieve MVP in the first place. I was trying to achieve an event-driven solution. My team-member has later directed me towards Martin Fowler's article on MVP. I was glad that the design was sane and was actually fitting into a paradigm. The key difference from MVP: In MVP view listens to presentors. In my case any entity can listen to any (chaining of listeners/models). The communication is via events Exception: Server-side communication, I wrote a dispatch controller layer (for unit test sake) contd:
    – questzen
    Commented May 15, 2010 at 17:42
  • Rational: I visualised my design as an telephone exchange. In real world, we can not have a telephone line between every handset: NC2 lines or N(N-1)/2. We connect to an exchange so only N lines are needed. Think of each line as a reference to listener, the object-reference propagation would be drastically reduced. IMO, MVP actually doesn't ask for a centralized exchange/bus. One can easily see the benefit of event bus (while coding) and use it. Banang's solution is a nice one. My solution was based on composition where as she used inheritance. A difference of opinion, I guess.
    – questzen
    Commented May 15, 2010 at 17:59
  • Thanks for the effort and insight, questzen. I think I understand it: as I go through actual implementation, I'll most certainly be in a better position to interpret the pros, cons, similarities and differences between MVP approaches. Commented May 17, 2010 at 17:20
0

have a look at: http://www.gwtproject.org/javadoc/latest/com/google/gwt/event/shared/EventBus.html

(which outdates http://www.gwtproject.org/javadoc/latest/com/google/web/bindery/event/shared/EventBus.html)

It should run fine with GWT as I'll try right now myself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.