To illustrate a simple example usage of the MVP pattern, consider the following code which creates a simple UI with only a button and a label. When the button is clicked, the label updates with the number of times the button has been clicked.
We have 5 classes:
Model - The POJO to maintain state (M in MVP)
View - The class with UI code (V in MVP)
ViewListener - Interface providing methods to responding to actions in the view
Presenter - Responds to input, and updates the view (P in MVP)
Application - The "main" class to pull everything together and launch the app
A minimal "model" class which just maintains a single count variable.
A minimal interface to notify the listeners:
The view class constructs all UI elements. The view, and only the view, should have reference to UI elements (ie. no buttons, text fields, etc. in the presenter or other classes).
The notification logic may also be coded like this in Java8:
The interface must be refactored in order to take the ActionEvent as a parametre:
Here only one notify-method is needed, the actual listener method and its parameter are passed on as parameters. In case needed this can also be used for something a little less nifty than actual event handling, it all works as long as there is a method in the interface, e.g.:
The presenter can take in the view and add itself as a listener. When the button is clicked in the view, the view notifies all listeners (including the presenter). Now that the presenter is notified, it can take appropriate action to update the model (ie. the state of the application), and then update the view accordingly.
To put everything together, the view can be created and injected into the presenter. Similarly, an initial model can be created and injected. While both can be created in the presenter, injecting them into the constructor allows for much simpler testing.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0