views:

439

answers:

2

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?

+2  A: 

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

questzen
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...
Tomislav Nakic-Alfirevic
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 eventsException: Server-side communication, I wrote a dispatch controller layer (for unit test sake)contd:
questzen
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
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.
Tomislav Nakic-Alfirevic
+8  A: 

One word: EventBus. The EventBus is your friend, and it will help you through this. This is how I did it:

My Eventbus class lets subscribers subscribe to events belonging to different modules in my app. There is of course different ways of doing this, if you want it more fine-grained 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.

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);
    }

}

One of my handlers (a bit of it). This handler deals with ClickEvents simply by 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)); 
    }

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;

A presenter (cut a bit short). 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);
    }
}

The principle behind the view is as follows: Each view is given an instance of a handler factory. The handler factry will create the correct handler based on what module the factory has been instantiated with. The view is then free to add handlers of different kind to it's components without having to know about the exact implementation details:

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*/ }

And there you have it, everything is nicely decoupled, and if you throw a couple of abstract classes and interfaces on it, none of your classes will ever really know what's going on. ;)

Please let me know if there's something you need me to clarify, I'm happy to do so.

Edit (Adding some clarifications as per your request):

The subscriber is the presenter. The presenter subscribes to events sent on the eventbus, and will react to the events by modifying the state of its view.

The "subscribing to modules"-bit is just something that's valid for my app, but I've found it's worked out very well for me. The Module is just an enum where all the different views in the system makes up one module.

For 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:

public enum Module 
{
   MENU,
   TEXT_AREA,
   CLASS_HIERARCHY
}

In my setup the deletion of a class file from the hierarchy would for example bring 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.

You would then have two presenters, the one controlling the tree view and the one controlling the text view, 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 Action class is also just an enum, and even though I did have the same concerns as you express in your comment when adding it, I find that just using a limited number of thinkable operations was enough for me, as each operation has the ability to mean slightly different things in each module.

This is my Action enum:

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

Of course, the alternative to this is using more specialised events and letting presenters subscribe to just these events, which probably is more durable if you plan on building a very big system. For the eclipse example above, this would mean that both the presenters for the hierarchy and the text area would subscribe to an event of a certain type, and in this case probably something like RemoveClassFileEvent or something similair.

Banang
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...
Tomislav Nakic-Alfirevic
I've edited my answer to answer your follow-up questions.
Banang
Banang, thanks for the effort and insight. I'll it a try and see how it goes...
Tomislav Nakic-Alfirevic
No problem! Best of luck to you, and if you have any follow-up questions I'd be happy to help you.
Banang