7. April 2010 15:49
In the second part of this blog posting (part 1 here) I’m going to examine the Model View Presenter (MVP) pattern. We’ll take a look at how the pattern can work, the pros/cons and an example of implementation. Please note that this is one example of how to implement the MVP pattern and this is not the only way you can do it. I am a big fan of this pattern and in a lot of cases this is my preferred way to develop UI’s.
The pattern is separated into 3 elements:
The actual user interface that displays data and receives commands from the user. This could be an ASP.NET WebForm, a WinForm, WPF page etc. The commands are handled by the view, but it passes the command to the presenter which contains the logic. This way multiple views can share the same presenter logic. The only time I put UI logic in the View is when that logic is specific only to that view (e.g. I would not put ASP.NET specific logic in the presenter – I would keep it in the UI).
Marshalls data between the View and the Model and vice versa. Receives commands from the view and performs UI logic e.g. validates and persists model data when a button is clicked.
The domain model representing the data of a particular system. In my example this is in the Business Layer (BL).
- Facilitates automated unit testing
- Allows multiple UIs to share the same presenter logic (DRY)
- Improves separation of concerns in UI code
- Can be implemented in most UI scenarios (WebForms, WinForms, WPF)
- Takes longer to design and implement than a traditional ‘Forms and Controls’ UI.
- Some thought required as to how much UI logic resides in the view and how much is in the presenter. It is more correct to have the logic in the presenter, but in some scenarios it will be more practical and pragmatic to have it in the view.
- Tight coupling between the View and the Presenter (unlike MVVM)
I have put together some sample code which demonstrates this pattern. The code shows how to implement multiple UIs from the same presenter – in this case a WinForms, WebForms and WPF UI. It also shows how to write unit tests against the presenter – in effect giving you a testable UI. Alternatively you could use one of the .NET MVP frameworks out there
Download the code as a VS 2008 solution.
Martin Fowler has proposed two variants of this pattern (Supervising Controller and Passive view)
MVC# – a .NET MVP framework
An excellent Code Project article describing how to implement the MVP pattern.
Any comments or feedback is welcome.