Introduction
MVP is a user interface architectural pattern engineered that follows the separation of concerns in the presentation logic. It is derived from the MVC design pattern. In MVC, all the presentation logic is moved to the presenter, hence make it suitable for automated unit testing. I will not go into the concept much since it is explained in many other places. Let us go with an example.
In the example, there are two views in the form, each with different colors.
Each view is extended from the IView interface as in the following:
- public interface IView
- {
-
-
-
- void LoadView();
-
-
-
-
- bool Validate();
-
-
-
-
- IPresenter Presenter { get; set; }
-
-
-
-
-
- void OnPropertyChanged(string propertyName);
- }
Corresponding to each view, there is a presenter and each presenter is driven from IPresenter as in the following:
- public interface IPresenter
- {
-
-
-
- void LoadData(PersonModel personModel, PersonPresenter mainPresenter);
- }
The Model is defined as:
- public class PersonModel
- {
- public string FirstName
- {
- get;
- set;
- }
- public string LastName
- {
- get;
- set;
- }
- public int Age
- {
- get;
- set;
- }
- public bool Married
- {
- get;
- set;
- }
- public string SpouseName
- {
- get;
- set;
- }
- public int Children
- {
- get;
- set;
- }
- }
There is a main presenter, which is exposed to the outer world and also defines the integration of Presenter and Views and put them in the form.
- public class PersonPresenter
- {
- Dictionary<string, IView> _views;
- PersonForm _personForm;
-
- public void LoadPersonUI(PersonModel person)
- {
- _personForm = new PersonForm();
- _views = new Dictionary<string, IView>();
-
- DetailsView detailsView = new DetailsView();
- detailsView.Presenter = new DetailsPresenter();
-
- _views.Add("Details", detailsView);
-
- FamilyView familyView = new FamilyView();
- familyView.Presenter = new FamilyPresenter();
-
- _views.Add("Family", familyView);
-
- foreach (string key in this._views.Keys)
- {
- Control viewControl = this._views[key] as Control;
- viewControl.Dock = DockStyle.Left;
- _personForm.Controls.Add(viewControl);
- viewControl.BringToFront();
- }
-
- foreach (string key in this._views.Keys)
- {
- _views[key].Presenter.LoadData(person, this);
- _views[key].LoadView();
- }
-
- _personForm.Show();
- }
-
- internal bool Validate()
- {
- foreach (string key in this._views.Keys)
- {
- if (!_views[key].Validate())
- return false;
- }
- return true;
- }
-
- internal void NotifyViewPropertyChanged(string propertyName)
- {
- foreach (IView view in _views.Values)
- view.OnPropertyChanged(propertyName);
- }
- }
This presenter is called from the outside world like this:
- PersonPresenter personPresenter = new PersonPresenter();
- personPresenter.LoadPersonUI(new PersonModel());
the code is attached here with this example, if something is not clear then please let me know.