Model View Presenter
Last updated
Was this helpful?
Last updated
Was this helpful?
Example code is available on .
This article shows an example of implementation. The basic idea is to show a way to split work with domain and service layer and UI view layer, not mixing all together.
Martin Fowler wrote great article worth reading about .
What are the roles of MVP.
Model represents database entities and provide way to manipulate with them.
View displays UI components and has no context of how the database is used to fetch data.
Presenter connect Model and View together, while only the presenter has the right to touch Model.
This example is intentionally simplified to easier understing of MVP implementation. We will create application that displays user name fetched from database.
Create domain model class for user entity. Run grails create-domain-class app.model.User
command to create User
class.
Now create service, by running grails create-service app.model.UserService
command, that will be used to manipulate with User
domain object.
Persist one user in BootStrap.groovy
to have a database record in database. We will use it later.
Now create a view to display details about user. We will never do any database operations in UserView
class but instead we provide methods to populate values in UI.
We could create an interface for
UserView
that will define all mandatory methods for that view. That would easier mocking ofUserView
in test and could give a way to make multiple implementations of user view.
Now we create presenter for UserView
. It will have reference to UserView
and UserService
.
The presenter will be responsible to add a view into navigator and to fetch values using UserService
.
Now we use UserPresenter
in our UI class to display user details.
Now we can run the application and user will appear in the browser.