«Back
Model-View-Presenter Pattern with Vaadin

The Model-View-Presenter (MVP) pattern is one of the most common patterns in developing large applications with Vaadin. It is similar to the older Model-View-Controller (MVC) pattern, which is not as meaningful in Vaadin development. Instead of an implementation-aware controller, there is an implementation-agnostic presenter that operates the view through an interface. The view does not interact directly with the model. This isolates the view implementation better than in MVC and allows easier unit testing of the presenter and model.

Figure 1. Model-View-Presenter Pattern

The Figure 1 illustrates the MVP pattern with a simple calculator. The domain model is realized in the Calculator class, which includes a data model and some model logic operations. The CalculatorViewImpl is a Vaadin implementation of the view, defined in the CalculatorView interface. The CalculatorPresenter handles the user interface logic. User interaction events received in the view are translated into implementation-independent events for the presenter to handle (the view implementation could also just call the presenter).

Let us first look how the model and view are bound together by the presenter in the following example:

// Create the model and the Vaadin view implementation
CalculatorModel    model = new CalculatorModel();
CalculatorViewImpl view  = new CalculatorViewImpl();
    
// The presenter binds the model and view together
new CalculatorPresenter(model, view);
    
// The view implementation is a Vaadin component
layout.addComponent(view);

You could add the view anywhere in a Vaadin application, as it is a composite component.

The Model

Our business model is quite simple, with one value and a number of operations for manipulating it.

	/** The model **/
class CalculatorModel {
    private double value = 0.0;
    
    public void clear() {
        value = 0.0;
    }

    public void add(double arg) {
        value += arg;
    }

    public void multiply(double arg) {
        value *= arg;
    }

    public void divide(double arg) {
        if (arg != 0.0)
            value /= arg;
    }
    
    public double getValue() {
        return value;
    }
    
    public void setValue(double value) {
        this.value = value;
    }
}

The View

The purpose of the view in MVP is to display data and receive user interaction. It relays the user interaction to the presenter in an fashion that is independent of the view implementation, that is, no Vaadin events. It is defined as a UI framework interface that can have multiple implementations.

	interface CalculatorView {
    public void setDisplay(double value);

    interface CalculatorViewListener {
        void buttonClick(char operation);
    }
    public void addListener(CalculatorViewListener listener);
}

The are design alternatives for the view. It could receive the listener in its constructor, or it could just know the presenter. Here, we forward button clicks as an implementation-independent event.

As we are using Vaadin, we make a Vaadin implementation of the interface as follows:

	class CalculatorViewImpl extends CustomComponent
        implements CalculatorView, ClickListener {
    private Label display = new Label("0.0");

    public CalculatorViewImpl() {
        GridLayout layout  = new GridLayout(4, 5);

        // Create a result label that spans over all
        // the 4 columns in the first row
        layout.addComponent(display, 0, 0, 3, 0);
    
        // The operations for the calculator in the order
        // they appear on the screen (left to right, top
        // to bottom)
        String[] operations = new String[] {
            "7", "8", "9", "/", "4", "5", "6",
            "*", "1", "2", "3", "-", "0", "=", "C", "+" };

        // Add buttons and have them send click events
        // to this class
        for (String caption: operations)
            layout.addComponent(new Button(caption, this));

        setCompositionRoot(layout);
    }
    
    public void setDisplay(double value) {
        display.setValue(Double.toString(value));
    }

    /* Only the presenter registers one listener... */
    List<CalculatorViewListener> listeners =
            new ArrayList<CalculatorViewListener>();

    public void addListener(CalculatorViewListener listener) {
        listeners.add(listener);
    }

    /** Relay button clicks to the presenter with an
     *  implementation-independent event */
    @Override
    public void buttonClick(ClickEvent event) {
        for (CalculatorViewListener listener: listeners)
            listener.buttonClick(event.getButton()
                                 .getCaption().charAt(0));
    }
}

The Presenter

The presenter in MVP is a middle-man that handles all user interaction logic, but in an implementation-independent way, so that it doesn't actually know anything about Vaadin. It shows data in the view and receives user interaction back from it.

	class CalculatorPresenter
        implements CalculatorView.CalculatorViewListener {
    CalculatorModel model;
    CalculatorView  view;

    private double current = 0.0;
    private char   lastOperationRequested = 'C';
    
    public CalculatorPresenter(CalculatorModel model,
                               CalculatorView  view) {
        this.model = model;
        this.view  = view;
        
        view.setDisplay(current);            
        view.addListener(this);
    }

    @Override
    public void buttonClick(char operation) {
        // Handle digit input
        if ('0' <= operation && operation <= '9') {
            current = current * 10
                    + Double.parseDouble("" + operation);
            view.setDisplay(current);
            return;
        }

        // Execute the previously input operation
        switch (lastOperationRequested) {
        case '+':
            model.add(current);
            break;
        case '-':
            model.add(-current);
            break;
        case '/':
            model.divide(current);
            break;
        case '*':
            model.multiply(current);
            break;
        case 'C':
            model.setValue(current);
            break;
        } // '=' is implicit

        lastOperationRequested = operation;

        current = 0.0;
        if (operation == 'C')
            model.clear();
        view.setDisplay(model.getValue());
    }
}

In the above example, we held some state information in the presenter. Alternatively, we could have had an intermediate controller between the presenter and the model to handle the low-level button logic.

Next
Comments
Trackback URL:

While this MVP princible is absolutely fine, I have two remarks concerning this example:
1. If you have a bigger application, it is cumbersome and too verbose to implement this pattern for each view and presenter. You find yourself looking for some kind of general MVP framework which abstracts and hides away much of the boilerplate.
2. Your example is not covering the common fact that in MVC/MVP applications multiple windows can show the same model content. So you need some kind of Observer-Pattern for model chances that will reflect in all views.
3. You will need lots of more general concepts around the presenters - i.e. communication between them, parent-child-relationships, view-composites (and therefore presenter-composites), creation and persistence of models...
Yes I know, too much for an example - but these are topics that mostly every project will run into - re-inventing the wheel again and again.

Posted on 7/3/13 9:45 AM.

Top
Thanks for your comment. I'll probably move this topic to the book at some point, as it is usually part of our courses. You are probably right, the example may be too simple for realistic cases. I'll try to add some steps to it when I can.

Oh, the comments on this page are shown white on white... I'll fix the CSS...

Posted on 7/4/13 12:53 PM in reply to Marco Missfeldt.

Top
Thank you Marko for you kind words... and by the way - white on white was difficult to read - indeed. ;-) But I did another funny thing: Writing about two remarks, and let follow three! :-)

Would be fine to find these topics in the book some day. If you should need some sparring partner in the wide field of MVC/MVP frameworking, please let me know. I would call myself a real expert when it comes to this. My last occupation at work was connecting the Vaadin UI system to a general MVC framework which also supports Swing, SWT and XHTML.

Posted on 7/4/13 6:32 PM in reply to Marko Grönroos.

Top
Hi, Thank you for the detailled demonstration about this. I have created an MVP framework based on the Spring addon (SpringVaadinIntegration) which will help using in the enterprise application. Created a full fledged maven project in Github which demonstrate this. This should solve the lack of a MVP framework in vaadin 7 with Spring. This is is an extended MVP pattern which has the following layers. View -> Presenter -> Service -> Dao All layers are loosely coupled. The view doesn't know about the Presenter. Both View and Presenter are scoped as prototype. The Spring service and Dao are singletons as the thumb rule. Plugin the EntityManager to your DaoImpl for persistence accordingly. Vaadin 7.1 SpringVaadinIntegration addon version 2.0.1 [url=https://github.com/rajeeshk/mvpcalculator]https://github.com/rajeeshk/mvpcalculator[url] Hope this will help. Please let me know if you have any comments/queries.

Posted on 8/5/13 3:16 PM.

Top