Image via Toptal
Model?view?presenter (MVP) is a derivation of the model?view?controller (MVC) architectural pattern which mostly used for building user interfaces. In MVP, the presenter assumes the functionality of the ?middle-man?. In MVP, all presentation logic is pushed to the presenter. MVP advocates separating business and persistence logic out of the Activity and Fragment
Differences between MVC and MVP
Model View Controller
- Controllers are behavior based and can share multiple views.
- View can communicate directly with Model
Model View Presenter
- View more separated from Model. The Presenter is the mediator between Model and View.
- Easier to create unit tests
- Generally there is a one to one mapping between View and Presenter, with the possibility to use multiple Presenters for complex Views
- Listen to user action and model updates
- Updates model and view as well
Model
In an application with a good layered architecture, this model would only be the gateway to the domain layer or business logic. See it as the provider of the data we want to display in the view. Model?s responsibilities include using APIs, caching data, managing databases and so on.
View
The View, usually implemented by an Activity, will contain a reference to the presenter. The only thing that the view will do is to call a method from the Presenter every time there is an interface action.
Presenter
The Presenter is responsible to act as the middle man between View and Model. It retrieves data from the Model and returns it formatted to the View. But unlike the typical MVC, it also decides what happens when you interact with the View.
Project Simple Workflow
Here, I try to illustrate the very basic of MVP pattern with simple demo android project which is available in GITHUB. The project has only one screen that have the username and email EditText and one TextView. When the user tries to input username or email, the input data will be shown in the top of the screen in TextView.
MainActivityPresenter.java
Here, MainActivityPresenter.java works as a middle man between view and model. It listen the user action, updates the data model and view.
User.java
MainActivity.java
Firstly, This activity implements the MainActivityPresenter.View Interface through which it?s overridden method will be called. Secondly, we have to create the MainActivityPresenter object with view as a constructor. We use this presenter object to listen the user input and update the data as well as view .
Output: