The MVP ( Model – View – Presenter) pattern can be seen as as an evolution or advanced form of the MVC (Model-View-Controller) pattern. It may not be easy to grasp from a programmatical point view at the begining, but the theory is pretty clear. To provide a better explanation of the MVP pattern, let’s compare it and contrast it with MVC. MVC allows decoupling the user interface components from the model. It uses the controller to switch from a view to another and to respond to events such as changing context, posting a form,..etc. However, The view can directly invoke functionalities from the model such as checking a value from the database or making a calculation. the view in MVP does not. MVP takes away the intelligence from the View and adds it to the controller which makes a Presenter. The view is completely passive and every interaction of the view with the model is done through the Presenter. Many argue that the main reason for using MVP over MVC is testability. By removing intelligence or business logic from the view, we reduce risk associated with not testing the view. Usually, unit tests are only applied to business logic and the model. So, MVP seems to be convenient for UI oriented applications such as the ones that are based on GWT. In this tutorial, we will go through an example of basic MVP pattern in a GWT application. Our application has two views: a login page and a main page. Upon successful login, the user is directed to the main page, and on logout the user goes back to the login page.
Requirements: Eclipse, GWT plugin.
The application structure looks something like:
Let’s start by implementing our views.
LoginView.java
MainPageView.java
Notice that the views are only UI components and do no contain any business logic.
Next, we need to build our presenters which will control the behavior and interactions of our views. LoginPresenter.java
MainPagePresenter.java
Notice that both presenters have an interface called Display. This interface needs to be implemented by the view to allow the Presenter to access components of the view. This interface serves as the communication layer between the Presenter and the View. We are going to make each view implements the Display interface of its presenter :
Finally, we need to implement the AppController, which is the application supervisor. It handles all events, and context changes. The AppController is also used to instantiate the application.