Model View Presenter
In the previous section of this tutorial, we discussed an alternate design pattern to MVC, Model View View-Model in which, we create a new component View Model that takes care of data manipulation tasks. However, we can have a better alternative since the view controller still does a lot of jobs, and therefore, a lack of distribution exists in MVC and also a bit in MVVM.
Also, the fact that a Controller is tightly linked to the view lifecycle, therefore, testing view controller becomes a tough task indeed. In this section of the tutorial, we will talk about another alternative design pattern, that is, MVP (Model View Presenter), which adds the main component presenter into the scheme of things.
What is the MVP?
Model View Presenter (MVP) is a design pattern that separates the objects into three main components: Model, View, and Presenter. Now, the View Controller is considered as View, and the presenter contains all the business logic of the application.
The MVP follows the passive view pattern; that is, all the actions will be forwarded to the presenter that updates the UI elements using delegates. The view will pass the actions and listen to the presenter updates. The presenter also updates the Model accordingly.
In this example, we will build a simple login application which follows MVP architecture. Here, we will create a Presenter, View Controller, and the UserModel.
In the storyboard of this project, we will add two views onto a view controller. On the first view, we will add two text fields to take the input from the user, and a submit button, and on the other view, we will display a success message. Initially, the second view will be hidden and will be displayed on the successful login.
In the above image, the inner view is shown in the storyboard. Now we will add another view above this view and make the background color black with the opacity of 60 %. It will look like the following image.
Now, we will come to the design pattern of the project. Here, we will follow the MVP as the design pattern. We will create the following folder structure in the project.
The LoginPresenter will contain all the business logic of the application. Its submitButtonClicked method will be triggered when the user clicks the submit button after entering the username and password. It does the validation and creates the model object on the confirmation. It also updates the UI via the delegate method implemented by the View Controller.