Presentation Model
Represent the state and behavior of the presentation independently of the GUI controls used in the interface
Also Known as: Application Model
19 July 2004
This is part of the Further Enterprise Application Architecture development writing that I was doing in the mid 2000’s. Sadly too many other things have claimed my attention since, so I haven’t had time to work on them further, nor do I see much time in the foreseeable future. As such this material is very much in draft form and I won’t be doing any corrections or updates until I’m able to find time to work on it again.
GUIs consist of widgets that contain the state of the GUI screen. Leaving the state of the GUI in widgets makes it harder to get at this state, since that involves manipulating widget APIs, and also encourages putting presentation behavior in the view class.
Presentation Model pulls the state and behavior of the view out into a model class that is part of the presentation. The Presentation Model coordinates with the domain layer and provides an interface to the view that minimizes decision making in the view. The view either stores all its state in the Presentation Model or synchronizes its state with Presentation Model frequently
Presentation Model may interact with several domain objects, but Presentation Model is not a GUI friendly facade to a specific domain object. Instead it is easier to consider Presentation Model as an abstract of the view that is not dependent on a specific GUI framework. While several views can utilize the same Presentation Model , each view should require only one Presentation Model . In the case of composition a Presentation Model may contain one or many child Presentation Model instances, but each child control will also have only one Presentation Model .
Presentation Model is known to users of Visual Works Smalltalk as Application Model

How it Works
The essence of a Presentation Model is of a fully self-contained class that represents all the data and behavior of the UI window, but without any of the controls used to render that UI on the screen. A view then simply projects the state of the presentation model onto the glass.
To do this the Presentation Model will have data fields for all the dynamic information of the view. This won't just include the contents of controls, but also things like whether or not they are enabled. In general the Presentation Model does not need to hold all of this control state (which would be lot) but any state that may change during the interaction of the user. So if a field is always enabled, there won't be extra data for its state in the Presentation Model .
Since the Presentation Model contains data that the view needs to display the controls you need to synchronize the Presentation Model with the view. This synchronization usually needs to be tighter than synchronization with the domain - screen synchronization is not sufficient, you'll need field or key synchronization.
To illustrate things a bit better, I'll use the aspect of the running example where the composer field is only enabled if the classical check box is checked.
Figure 1: Classes showing structure relevant to clicking the classical check box
Figure 2: How objects react to clicking the classical check box.
When someone clicks the classical check box the check box changes its state and then calls the appropriate event handler in the view. This event handler saves the state of the view to Presentation Model and then updates itself from the Presentation Model (I'm assuming a coarse-grained synchronization here.) The Presentation Model contains the logic that says that the composer field is only enabled if the check box is checked, so the when the view updates itself from the Presentation Model , the composer field control changes its enablement state. I've indicated on the diagram that the Presentation Model would typically have a property specifically to mark whether the composer field should be enabled. This will, of course, just return the value of the isClassical property in this case - but the separate property is important because that property encapsulates how the Presentation Model determines whether the composer field is enabled - clearly indicating that that decision is the responsibility of the Presentation Model .
This small example is illustrates the essence of the idea of the Presentation Model - all the decisions needed for presentation display are made by the Presentation Model leaving the view to be utterly simple.
Probably the most annoying part of Presentation Model is the synchronization between Presentation Model and view. It's simple code to write, but I always like to minimize this kind of boring repetitive code. Ideally some kind of framework could handle this, which I'm hoping will happen some day with technologies like .NET's data binding.
A particular decision you have to make with synchronization in Presentation Model is which class should contain the synchronization code. Often, this decision is largely based on the desired level of test coverage and the chosen implementation of Presentation Model . If you put the synchronization in the view, it won't get picked up by tests on the Presentation Model . If you put it in the Presentation Model you add a dependency to the view in the Presentation Model which means more coupling and stubbing. You could add a mapper between them, but adds yet more classes to coordinate. When making the decision of which implementation to use it is important to remember that although faults do occur in synchronization code, they are usually easy to spot and fix (unless you use fine-grained synchronization).
An important implementation detail of Presentation Model is whether the View should reference the Presentation Model or the Presentation Model should reference the View. Both implementations provide pros and cons.
A Presentation Model that references a view generally maintains the synchronization code in the Presentation Model . The resulting view is very dumb. The view contains setters for any state that is dynamic and raises events in response to user actions. The views implement interfaces allowing for easy stubbing when testing the Presentation Model . The Presentation Model will observe the view and respond to events by changing any appropriate state and reloading the entire view. As a result the synchronization code can be easily tested without needing the actual UI class.
A Presentation Model that is referenced by a view generally maintains the synchronization code in the view. Because the synchronization code is generally easy to write and easy to spot errors it is recommended that the testing occur on the Presentation Model and not the View. If you are compelled to write tests for the view this should be a clue that the view contains code that should belong in the Presentation Model . If you prefer to test the synchronization, a Presentation Model that references a view implementation is recommended.
When to Use It
Presentation Model is a pattern that pulls presentation behavior from a view. As such it's an alternative to to Supervising Controller and Passive View . It's useful for allowing you to test without the UI, support for some form of multiple view and a separation of concerns which may make it easier to develop the user interface.
Compared to Passive View and Supervising Controller , Presentation Model allows you to write logic that is completely independent of the views used for display. You also do not need to rely on the view to store state. The downside is that you need a synchronization mechanism between the presentation model and the view. This synchronization can be very simple, but it is required. Separated Presentation requires much less synchronization and Passive View doesn't need any at all.
Example: Running Example (View References PM) (C#)
Here's a version of the running example , developed in C# with Presentation Model .
Figure 3: The album window.
I'll start discussing the basic layout from the domain model outwards. Since the domain isn't the focus of this example, it's very uninteresting. It's essentially just a data set with a single table holding the data for an album. Here's the code for setting up a few test albums. I'm using a strongly typed data set.
The Presentation Model wraps this data set and provides properties to get at the data. There's a single instance of the Presentation Model for the whole table, corresponding to the single instance of the window. The Presentation Model has fields for the data set and also keeps track of which album is currently selected.
class PmodAlbum...
PmodAlbum provides properties to get at the data in the data set. Essentially I provide a property for each bit of information that the form needs to display. For those values which are just pulled directly out of the data set, this property is pretty simple.
The title of the window is based on the album title. I provide this through another property.
I have a property to see if the composer field should be enabled.
This is just a call to the public IsClassical property. You may wonder why the form doesn't just call this directly - but this is the essence of the encapsulation that the Presentation Model provides. PmodAlbum decides what the logic is for enabling that field, the fact that it's simply based on a property is known to the Presentation Model but not to the view.
The apply and cancel buttons should only be enabled if the data has changed. I can provide this by checking the state of that row of the dataset, since data sets record this information.
The list box in the view shows a list of the album titles. PmodAlbum provides this list.
So that covers the interface that PmodAlbum presents to the view. Next I'll look at how I do the synchronization between the view and the Presentation Model . I've put the synchronization methods in the view and am using coarse-grained synchronization. First I have a method to push the state of the view into the Presentation Model .
class FrmAlbum...
This method is very simple, just assigning the mutable parts of the view to the Presentation Model . The load method is a touch more complicated.
The complication here is avoiding a infinite recursion since synchronizing causes fields on the form to update which triggers synchronization.... I guard against that with a flag.
With these synchronization methods in place, the next step is just to call the right bit of synchronization in event handlers for the controls. Most of the time this easy, just call SyncWithPmod when data changes.
Some cases are more involved. When the user clicks on a new item in the list we need to navigate to a new album and show its data.
Notice that this method abandons any changes if you click on the list. I've done this awful bit of usability to keep the example simple, the form should really at least pop up a confirmation box to avoid losing the changes.
The apply and cancel buttons delegate what to do to the Presentation Model .
So although I can move most of the behavior to the Presentation Model , the view still retains some intelligence. For the testing aspect of Presentation Model to work better, it would be nice to move more. Certainly you can move more into the Presentation Model by moving the synchronization logic there, at the expense of having the Presentation Model know more about the view.
Example: Data Binding Table Example (C#)
As I first looked at Presentation Model in the .NET framework, it seemed that data binding provided excellent technology to make Presentation Model work simply. So far limitations in the current version of data binding holds it back from places that I'm sure it will eventually go. One area where data binding can work very well is with read-only data, so here is an example that shows this as well as how tables can fit in with a Presentation Model design.
Figure 4: A list of albums with the rock ones highlighted.
This is just a list of albums. The extra behavior is that each rock album should have it's row colored in cornsilk.
I'm using a slightly different data set to the other example. Here is the code for some test data.
The presentation model in this case reveals its internal data set as a property. This allows the form to data bind directly to the cells in the data set.
To support the highlighting, the presentation model provides an additional method that indexes into the table.
This method is similar to the ones in a simple example, the difference being that methods on table data need cell coordinates to pick out parts of the table. In this case all we need is a row number, but in general we may need row and column numbers.
From here on I can use the standard data binding facilities that come with visual studio. I can bind table cells easily to data in the data set, and also to data on the Presentation Model .
Getting the color to work is a little bit more involved. This is straying a little bit away from the main thrust of the example, but the whole thing gets its complication because there's no way to have row by row highlighting on the standard WinForms table control. In general the answer to this need is to buy a third party control, but I'm too cheap to do this. So for the curious here's what I did (the idea was mostly ripped off from http://www.syncfusion.com/FAQ/WinForms/). I'm going to assume you're familiar with the guts of WinForms from now on.
Essentially I made a subclass of DataGridTextBoxColumn which adds the color highlighting behavior. You link up the new behavior by passing in a delegate that handles the behavior.
class ColorableDataGridTextBoxColumn...
The constructor takes the original DataGridTextBoxColumn as well as the delegate. What I'd really like to do here is to use the decorator pattern to wrap the original but the original, like so many classes in WinForms, is all sealed up. So instead I copy over all the properties of the original into my subclass. This won't work is there are vital properties that can't be copied because you can't read or write to them. It seems to work here for now.
Fortunately the paint method is virtual (otherwise I would need a whole new data grid.) I can use it to insert the appropriate background color using the delegate.
To put this new table in place, I replace the columns of the data table in the page load after the controls have been built on the form.
class FrmAlbums...
It works, but I'll admit it's a lot more messy than I would like. If I were doing this for real, I'd want to look into a third party control. However I've seen this done in a production system and it worked just fine.

Nov 20, 2017
The Presentation Model
Let’s look at a common challenge in MVC, and a thirty year old solution. We’ll contrast it with MVVM, and then wrap up with tradeoffs.
We’ll use the Messages inbox as an example.
Preface: What Is and Isn’t MVC?
Stop me if you’ve heard this:
MVC is terrible! We had a massive view controller with networking, collection view layouts, and image caching. We moved away from MVC and everything was fixed!
This isn’t a strike against MVC, but our failure to teach it. When a controller contains network, storage, or layout code, it isn’t MVC. It’s ‘View and a Ball of Mud.’
The view is about presentation, including drawing, layout, and animation. The model is about the business rules, including talking to your backend. The controller is mostly glue that sits between the view and the model. It sets up the scene, and then interprets the events on either side.
Before we try a new design pattern, let’s work out the basics.
Our MVC Design
- Model: We start with a MessageStore . It has a fetchAllConversations() method, that returns an array of Conversation objects. Each thread contains an array of Message objects.
- View: A tableview with a MessageCell table view cell.
- Controller: The datasource for the tableview.
Behind the scenes, when a new message arrives, the MessageStore receives a push notification, and checks a REST endpoint for new messages. Or not. It’s an implementation detail abstracted behind the model.
We have a requirement that each conversation in our inbox shows a preview of the most recent message. It updates when a new message arrives in a conversation. Let’s walk through the flow.
When a new message arrives, MessageStore notifies our controller. We could use a delegate or NSNotificationCenter , but it’s really up to you.
Now let’s address common problems.
Problem 1: Complex Display Rules
Let’s add a few rules around how data is displayed:
- In that message preview, if the most recent message is a photo, display ‘ Attachment: 1 Image.’ Otherwise, show the text of the message.
- If the timestamp was today, show the time, like ‘ 10:00 am’. If it’s before today, show the day, like ‘ Yesterday .’
“Hmm. We’re describing display, why not throw this in MessageCell ?”
A few months later your company asks for an iPad app with a radically different cell design. To share these display rules, do you subclass MessageCell into PhoneMessageCell and PadMessageCell ?
Then your company asks for a native Mac app. (Hey, this is fantasy.) MacOS doesn’t use UITableViewCell , so you can’t just create a MacCell subclass.
You could throw this logic inside your controller, but we’re back to violating MVC, and besides, there’s no UIViewController on the Mac.
Problem 2: Display State
Then there’s the search box. We need to keep track of the search string, but it’s a bad idea to treat UITextField 's text property as the source of truth. For example, we might recycle views for performance reasons, and every iOS developer knows the self-inflicted pain of cell recycling bugs.
You could keep track of this state in the view controller, but it introduces the tight coupling from earlier.
Problem 3: Testing
Let’s say you want to test message searching, to make sure it’s a case insensitive search. With business logic inside UIViewController , you need a large swatch of dependencies in your test harness.
In addition to slowing down your test suite, your search tests might break when there’s another unrelated failure with MessageCell . Cascading test failures make it harder to track down what precisely broke.
Introducing the Presentation Model
As far back as 1988, Smalltalk developers realized there are really two types of models in the an app: the Domain Model, which deal with business logic, and the Application Model , which deals with how it’s represented on screen. The latter is bit ambiguous, so I prefer Martin Fowler’s 2004 rebranding , a Presentation Model .
For example, Message is a high level concept, and belongs in our domain model. Timestamp formatting rules, and keeping track of search text, belong in our presentation model.
For clarity, I’ll add a Presentation suffix.
It encapsulates Conversation and exposes previewText property to wrap formatting rules.
Rather than tie it to Conversation , we could create a ConversationPresentable protocol. In our test suite, we’d pass it FakeConversation to flex all the rules.
We could also stash search state in an InboxPresentation object. Let’s start with a bit of refactoring.
For brevity I’ve omitted the Notification Center details. In a nutshell, our view controller subscribes to this inbox object. When the message store updates, our inbox refreshes its conversations array.
Now we can add search behavior:
Our view controller just reads:
In addition to cleaning up our view controller, we’ve hidden details about the entities involved when filtering messages. Later we can refactor things to make a single SQL call directly to our database.
Be aware that a Presentation Model is different than a Presenter you might hear about. Apple’s MVC is technically a Model-View-Presenter pattern. For whatever reason, Apple rebranded it. If you see Presenter think Controller . If you see Presentation Model, that’s the thing we just discussed.
Strictly speaking, Fowler’s Presentation Model receives all events. You aren’t using his Presentation Model if your view controller is a delegate for a view. I consider this a minor distinction. Even within MVC, you have a spectrum between “Passive View” and “Supervising Controller.” I think there’s a much more loaded term to avoid…
What about MVVM?
If you read too many iOS blogs, by now you’re saying , “This sounds a lot like MVVM.” People keep saying MVVM, but I do not think it means what they think it means. If you’re interested in software anthropology, read on. Otherwise skip to ‘Trade Offs’ at the end.
Fowler leaves a few details up in the air:
A particular decision you have to make with synchronization in Presentation Model is which class should contain the synchronization code.
In 2005, Microsoft took Fowler’s idea and ran with it. They codified MVVM with an ambitious goal :
[MVVM] is tailored for modern UI development platforms where the View is the responsibility of a designer rather than a classic developer. The designer is generally a more graphical, artistic focused person, and does less classic coding than a traditional developer. The design is almost always done in a declarative form like HTML or XAML, and very often using a WYSIWYG tool such as Dreamweaver, Flash or Sparkle.
Microsoft admits it was inspired by the presentation model:
It looks surprisingly similar to the Presentation Model pattern … In fact, the pretty much the only difference is the explicit use of the databinding capabilities of WPF and Silverlight.
They imagined engineers would just toss a ViewModel to their designer, and the designer could build a GUI around it without writing any code. They accomplish this through the largest defining characteristic of MVVM: data bindings .
But Microsoft markets MVVM as much more than “a useful design pattern that leverages bindings.” Microsoft sells MVVM as their platform’s alternative to MVC :
In some ways the MVVM pattern is similar to the Model-View-Presenter (MVP) pattern … both patterns are variants of the Model-View-Controller (MVC) pattern, both are Separated Presentation patterns, and both are designed to isolate the details of the user interface from the underlying business logic in order to enhance manageability and testability.
This brings us to the second big characteristic of MVVM: the ViewModel replaces the Controller. It’s MVVM, not MVMVC.
The view model also provides implementations of commands that a user of the application initiates in the view.
Then there’s MVVM as misunderstood by too many iOS developers. Most iOS examples don’t use bindings— which makes sense given iOS doesn’t provide them.
In many examples, the view controller still acts as the central hub for events. That makes sense since only controllers gets essential events like viewDidAppear and rotation events. There’s no escaping MVC.
Most people say MVVM when they’re really talking about something much closer to a Presentation Model. ‘iOS MVVM’ is a reflection of a reflection. It’s WaLuigi .
Do these semantics matter?
“Does it matter that people say MVVM when they really mean presentation model? Even Apple says MVC when they really mean MVP.”
If your team already calls your presentation model a “View Model,” it isn’t worth the disruption to rename everything. For all I care, call it a Cupcake Model.
However, as you’ve noticed by me repeating “Apple’s MVC,” it’s confusing when someone co-opts an existing term. Unfortunately, it’s crazy to insist Apple rename UIViewController to UIViewPresenter in their code. But the ship hasn’t sailed for your team.
I know this is bike shedding, but if I need a suffix for these types models, I lean toward ‘presentation.’ Why?
- ViewModel’s overloaded meaning adds noise to Google results
- Presentation describes the object’s responsibilities. See Managers
- It’s a tiny thing, but but “Open Quickly” produces fewer results with “pres” than “view.”
The Trade Offs
It’s important to stress that a presentation model is not a new architecture. Don’t stick it in every project and say you practice MPVC.
Consider a todo list app. You have a Task object, and decide to add TaskPresentation.
You end up with a lot of boilerplate with no added value. Could Swift provide tools to make this easier? Let’s not go there.
Next, we have questions like, “Would an unread property belong in the presentation layer or domain layer?” Watch out, or you’ll end up with behavior randomly split between two locations. That can be worse than the original problems.
Finally, there’s the old saying, “All problems in computer science can be solved by another level of indirection, except for the problem of too many layers of indirection.”
In our previous example, we had ConversationPresentation , but what if we add another presentation model for the conversation screen? We’d end up with ConversationInboxPresentation and ConversationDetailPresentation . This sounds like enterprise software.
In a real project, start with a simple set of entities. Don’t introduce a presentation model just to wrap a couple of if statements. Anyone who says “Everything must be tested” lives in a fantasy. But hey, this is subjective.
Special thanks to Kumara Krishnan for reviewing the MVVM portion of this post.
More from Ben Sandofsky
Developer at Lux Optics. We build photography apps like Halide and Spectre.
About Help Terms Privacy
Get the Medium app

Ben Sandofsky
Text to speech
- Development
- Presentation Patterns : MVC, MVP, PM, MVVM
In this blog post, I will explain different presentation patterns, why do we need these patterns and how to use them. Why do we need these patterns ?
Why do we need these patterns in the first place ? Well one can certainly build software applications without using any of these patterns, but by using these patterns we can achieve separation of concerns design principle. These help in improving maintainability of the application. Another important reason why these patterns became popular is implementing these patterns improve the testability of the application using automated unit tests. We all know how difficult it is to write unit tests for UI tier, these patterns try to address some of these difficulties and provide a way of increasing application’s testability.
As the name suggests these are applicable to only Presentation tier. Model View Controller (MVC) was the first pattern that was developed by Trygve Reenskaug in 1979 for SmallTalk applications. It was developed to build the complete applications not only the presentation layer. Those days there were no UI controls and everything had to be drawn from scratch and handle interaction between your program and user input devices such as keyboard. P resentation layer has changed a lot since then, so did the definition of the pattern. Today’s MVC pattern definition doesn’t exactly match the original definition. A number of variations of this pattern have been adapted.
I will explain the classic MVC pattern first and then introduce a web variant of it, known as Model 2, then move on to MVP, explain the two different variations of MVP pattern and then Presentation Model (PM) and its variant MVVM. The below diagram from “Architecting Applications for the Enterprise” by Dino Esposito and Andrea Saltarello’s book depicts the main presentation patterns and their variations

The Classic Model-View-Controller Pattern (MVC):
The following diagram depicts the structure of MVC pattern

In MVC pattern, model, view, controller triad exists for each object that can be manipulated by the user. Lets see what each of these does
Model : Model means data, that is required to display in the view. It can sometimes be the exact data entities that are retrieved from the business layer or a variation of it. Model encapsulates business tier.
View : View is something that displays data to user. In MVC pattern view should be simple and free of business logic implementation. View invokes methods on Controller depending on user actions. In MVC pattern View monitors the model for any state change and displays updated model. Model and View interact with each other using the Observer pattern.
Controller: Controller is invoked by view, it executes interacts with the model and performs actions that updates the model. Controller doesn’t have an idea about the changes that it’s updates on the model resulted in the view. Often misunderstood in MVC pattern is the role of Controller. It doesn’t mediate between the view and model,and its not responsible for updating the view. It simply process the user action and updates model, its the view’s job to query and get the status of the changed model and render it. The only time Controller comes into picture is if a new view has to be rendered.
A more easier way of understanding the interaction between Model, View and Controller is using a sequence diagram, which I took from Dino Esposito’s excellent book.

In Classic MVC pattern Model and View are bound according to the rules of Observer pattern. This is one of the major drawback of Classic MVC pattern. The Classic MVC pattern is no longer in use today. Model2 is a popular variant of MVC pattern that is used in web applications
MVC Pattern for Web Applications (Model 2)
Classic MVC pattern was designed when web didn’t exist and it was primarily designed for desktop applications (We are talking about the 70’s :-)), but the loose definition of MVC made way to different variations of MVC. One of the most popular variation is Model 2. It’s a pattern originally created for Java Server Pages (JSP) and owes a lot of its popularity to Struts framework. It’s the same pattern implemented by the recent ASP.NET MVC framework in .NET technology stack.
In Model 2 pattern, all web post requests go to front controller, implemented as a http interceptor (http module in ASP.NET ),which in turn figures out the appropriate controller depending on the structure of the incoming request URL and services the request. The controller invokes a method that affects the model.
The following diagram depicts the structure of Model2 pattern:

The main difference between classic MVC and Model2 is that t here is no direct contact between view and model. The Model in this pattern is not your typical business entities or Business layer, it’s more of a ViewModel that captures the state of the view. The controller will be the one who will talk to BLL and update the model. The interaction between the view and model is an indirect relationship.
Below sequence diagram depicts Model2 interactions using sequence diagram :

Model2 is the most popular variant of MVC pattern applied to web applications, Model2 is MVC adapted to web.
Model View Presenter (MVP)
Classic MVC pattern has two drawbacks:
- Model needs to communicate change of state to the view
- The view has complete knowledge of the model, there is no explicit contract between view and model , which means the view is not as passive as it should be.
Model View Presenter (MVP) pattern evolved from MVC, it tries to address the above concerns. MVP was originally developed at Taligent, in 90’s. The original MVP is also no longer in use today. According to Martin Fowler, you never use MVP, rather you use Passive View or Supervising Controller or both variants.
The MVP pattern neatly separates the Model from the View and breaks the direct relationship between them. The core of MVP is the interaction between View and Presenter. The View exposes a contract(interface in .NET) through which the Presenter interacts with the View. When users interact with the view, the view invokes a method on the presenter and the presenter performs the required task on the Model and then updates the View using the contract.
Below sequence diagram depicts the MVP pattern in action

Model : Model in MVP represents business entities or domain model or object model of the business tier.
View : In MVP pattern, View is light weight. It should only have the UI elements and shouldn’t be aware of the model. But that is in a ideal scenario, building a real passive view is quite complex in practice, hence the implementation of MVP falls into two categories : 1. Passive View : The view is really passive, light weight. View doesn’t know the model
The below triad diagram aptly depicts the Passive View pattern

2. Supervising Controller The view is active, binds the view using data binding or simple code in view View doesn’t know the model
The below triad diagram depicts Supervising Controller pattern in action.

Presenter : Why Presenter? Why the name change? The classic MVP triad diagram looks similar to MVC diagram, the noticeable difference is Controller replaced with Presenter. It’s not a case of just name change. The Presenter in MVP, presents user actions to the backend system; after getting the response it presents the response to the users, whereas the Controller in the MVC pattern doesn’t mediate between Model and the View, it doesn’t update the view, it just mediates between user actions and model.
MVP became quite popular in .NET world. Though it involves significant effort in using MVP pattern to build UI applications it pays of while building large scale enterprise applications, but probably a over kill for small applications.
Presentation Model (PM) Martin Fowler developed Presentation Model pattern for Presentation layer. So what’s the difference between MVP and PM ? It adheres to the same fundamental principle, Separation of Concerns. It differs in the view Model is defined and the tasks Presenter performs.
This particular pattern is well suited for rich UI applications and it really suits the latest advances in UI technologies. Presentation Model suits well for WPF and Silverlight applications. MVVM is the variation of PM pattern implemented in WPF and Silverlight.

In MVP, Presenter talks to the View using a contract (interface in .NET) , but in PM the view doesn’t implement any interface. The view elements are directly bound to properties on the model. In PM, the view is passive.The Presenter goes by the name Presentation Model in this pattern.
Model: Here the Model is not your typical business entities or business objects it represents the state of the view, it might contain UI elements specific properties and once the model is constructed, view will be ready for rendering.
View : View is light weight and simple. It will contain only UI specific elements. Any events raised by the user are transmitted to the presenter (Presentation Model) , the Presentation Model, updates the model with the results it gets. The presenter after updating the model orders the view to render. Presenter: The presenter in PM receives events from view, processes them, updates the model as in MVP or MVC, but the difference is in PM the presenter holds the model object and its responsible for updating the state changes and calling the view to render once the model is updated.
Model View View Model (MVVM) In 2005, John Gossman, Architect at Microsoft, unveiled the Model-View-ViewModel (MVVM) pattern on his blog. MVVM is identical to Fowler’s Presentation Model, in that both patterns feature an abstraction of a View, which contains a View’s state and behavior. Fowler introduced Presentation Model as a means of creating a UI platform-independent abstraction of a View, whereas Gossman introduced MVVM as a standardized way to leverage core features of WPF and Silverlight to simplify the creation of user interfaces. MVVM is a specialization of the more general PM pattern, tailor-made for the WPF and Silverlight platforms to leverage core features of WPF such as data binding, commands , templates.
This diagram take from MSDN depicts MVVM Pattern in action.

View : View in MVVM is similar to view in PM. It contains only the UI elements. The interaction between view and ViewModel happens using Data Binding, Commands and Notifications implemented through INotifyPropertyChanged interface. ViewModel: View Model is equivalent to PresentationModel in PM pattern, it encapsulates presentation logic and data for the view. ViewModel contains the state of the view and uses Commands , DataBinding and Notifications to communicate with the view. Model : Model is Business logic layer of the application
When you use MVVM pattern for WPF, Silverlight the view wouldn’t have the typical event handlers that’s so common in UI code, All user actions are bound to commands, which are defined in the ViewModel and invoke the necessary logic to update the model. This improves unit testability of MVVM applications.
Conclusion: MVC, MVP, PM, MVVM all are different ways of implementing the Separation of Concerns (SoC) principle. The different variants show how the pattern changed with the changes in UI technologies in both desktop and web applications. As long as you understand the fundamental SoC principle you would easily understand these patterns.
Share this:
From → Development
Leave a Reply Cancel reply
Fill in your details below or click an icon to log in:
You are commenting using your WordPress.com account. ( Log Out / Change )
You are commenting using your Twitter account. ( Log Out / Change )
You are commenting using your Facebook account. ( Log Out / Change )
Connecting to %s
Notify me of new comments via email.
Notify me of new posts via email.
Recent Posts
- Test Driven Development
- Design Principles and Patterns
- Cloud Computing : An overview
Create a free website or blog at WordPress.com.

- Already have a WordPress.com account? Log in now.
- Follow Following
- Copy shortlink
- Report this content
- View post in Reader
- Manage subscriptions
- Collapse this bar

Principal Serverless Specialist Solutions Architect at AWS, International Speaker, O'Reilly author
Presentation Model design pattern: multiple screen solution – part 1
Today I’d like to talk about Presentation Model design pattern because it’ll be so useful for anyone that is working on multiple screen project with Flash or Flex. In latest months we lived in phrenetic mobile world where we have tons of new and powerful devices on the market with different screen sizes, different hardware and so on, on the other hand we have clients that are looking for new business opportunities and they are seeking a way to spend less but earn more. So, one way to solve those problems could be find a way to deploy with the same technology in different devices (tablets, smartphones, computers…) saving time with great results! That’s not a dream, it could be made with knowledge, architecture and a good developer or a team!
For a developer find a way to have a good project architecture to maintain it’s so important, usually when you start a project you try to define the parts that could be re-usable in different part of the same project or in different project too. So our aim is find a way to write less code but it will cover the project needs and that could be portable in different screens / operating systems easily.
What is Presentation Model design pattern?
My mentor Martin Fowler describes it with those words: “ Represent the state and behavior of the presentation independently of the GUI controls used in the interface ” (here the full article of Martin Fowler). In fact with this pattern we divide UI (components, movieclips, sprites…) from their behaviors; each view will have one and only that one presentation model and only the presentation model will interact with the whole architecture (like with model or proxy…). Probably with this image you can easily understand better this concept (from Martin Fowler website):
Like you can see we have 3 class, AlbumTitle that is a view with a textfield, AlbumPresentationModel that is the presentation model of AlbumTitle and it has the copy of the view but storing datas inside and finally the main model Album where we have the data that could be used for the whole application. There aren’t any connection trough the views and the application model because only the presentation model has access to the whole project, so the view is only a bunch of components and custom graphics, this it means that if you have to change UI on a mobile project for a different device, changing the views and anything else, you will have done your job. In fact with this easy technique you perfectly solve our problem and you should create the same content for different devices changing only the views. Probably your application in different devices will have the same functionalities but with a different UI dedicated for the OS is running on. With this sample design pattern you’ll have a solid infrastructure that will solve the big problem to port the same application in different screen sizes. So in next paragraph we can take a look on how to organize our files project.
Manage a project for different screen sizes
Another important thing before starts the project is understand how to organize the project for different OS, in fact if you work with Adobe AIR on Android you’ll have only the XML descriptor with Android permissions described in this file, on Playbook you’ll have another XML file dedicated to this platform and so on. So, my suggestion is to organize the project in different projects that work together. In this image you can see how I organize it for our final scope, I’ve a common project (Runtime Shared Libraries in this case but you can use also an Actionscript or AIR project if you work with Flash for example) where I’ll put all classes that are common for different target, so in my case all the presentation models, main models, utils classes, my notification bus and views that are common for different projects like components for example.

In the target device projects I add only what I need for that device, in this case only a couple of views and assets but in big projects could be more stuff that those one:

When you have a specific behavior only for a target device, you can easily extends the common presentation model and add new functionalities or create a side class that you’ll add in the specific view. So with this infrastructure you can solve bugs and change stuff directly on the common project and all the platforms will be ready to package the project and upload to their store. That’s cool, isn’t it?
So in this post I hope to give you some ideas on how to solve the big problem to create a common base code that could be useful for different purpose. In next post I’ll show you how to implement it in practice, for now if you have any feedback or suggestions for the second part of this article please add a comment to this post.
Share this:
Published by.
luca mezzalira
Being associated with the industry since 2004, I have lent my expertise predominantly in the solution architecture field. I have gained accolades for revolutionising the scalability of frontend architectures with micro-frontends, from increasing the efficiency of workflows, to delivering quality in products. My colleagues know me as an excellent communicator who believes in using an interactive approach for understanding and solving problems of varied scopes. I helped DAZN becoming a global streaming platform in just 5 years, now as Principal Architect at AWS, I'm helping our customers in the media and entertainment space to deliver cost-effective and scalable cloud solutions. Moreover, I'm sharing with the community the best practices to develop cloud-native architectures solving technical and organizational challenges. My core industry knowledge has been instrumental in resolving complex architectural and integration challenges. Working within the scopes of a plethora of technical roles such as tech lead, solutions architect and CTO, I have developed a precise understanding of various technicalities which has helped me in maximizing value of my company and products in my current leadership roles. View all posts by luca mezzalira
2 thoughts on “Presentation Model design pattern: multiple screen solution – part 1”
Thanks , it is great . looking forward to see next part in practice.
- Pingback: » A touchless touch-screen may soon reach the market
Leave a Reply Cancel reply
Fill in your details below or click an icon to log in:
You are commenting using your WordPress.com account. ( Log Out / Change )
You are commenting using your Twitter account. ( Log Out / Change )
You are commenting using your Facebook account. ( Log Out / Change )
Connecting to %s
Notify me of new comments via email.
Notify me of new posts via email.

- Already have a WordPress.com account? Log in now.
- Follow Following
- Copy shortlink
- Report this content
- View post in Reader
- Manage subscriptions
- Collapse this bar
Hugo V. Teixeira
A little bit about coding, user interfaces, computer graphics and component-based software engineering., advantages of the presentation model pattern.
This article explains the advantages of the Presentation Model pattern over the Model-View-Controller and Model-View-Presenter. This will improve your decisions about GUI implementations for desktop.
One of the major challenges in the development of desktop software is the effective use of unit tests that cover the GUI functionalities and its interactions with the remainder of the software. The complexity of this implementation lies in the control of selected items in lists and tables, modal dialogs, clicks and events. In fact, it is extremely difficult to develop good tests on the GUI when the application logic is tightly-coupled to UI components.
You probably have already heard about design patterns that could help in this case, especially those that separate the application logic from UI components. Perhaps the most famous is the Model-View-Controller (MVC), which has been widely used not only for desktop applications but also for web development.
There is a relevant question that we should ask ourselves at this point: Is this separation between logic and UI components enough to reduce the complexity of writing GUI unit tests?
Figure 1 presents the three most important presentation patterns for desktop development. Besides the MVC, there is one called Model-View-Presenter (MVP) that consists of a small variation of the first one (see Martin Fowler’s description of them for more details).

Figure 1: Patterns for desktop application development.
The important thing to notice in this picture is that both MVC and MVP describe the controller/presenter with a reference to the view. So, to create an instance of the controller inside the test code, we need the view as well. This still makes the development of unit tests difficult.
There is a turnaround to this problem, which is basically to add an interface between the controller and the view to break this dependency and abstract the view’s components. But the idea behind this solution increases the amount of code and does not imply in less complexity and clean organization. In most of the cases, this resolution is not worth the effort when there is a third option such as the Presentation Model pattern.
Share this:
Leave a reply cancel reply.
Fill in your details below or click an icon to log in:
You are commenting using your WordPress.com account. ( Log Out / Change )
You are commenting using your Twitter account. ( Log Out / Change )
You are commenting using your Facebook account. ( Log Out / Change )
Connecting to %s
Notify me of new comments via email.
Notify me of new posts via email.

- Already have a WordPress.com account? Log in now.
- Follow Following
- Copy shortlink
- Report this content
- View post in Reader
- Manage subscriptions
- Collapse this bar
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
- 21 minutes to read
Design Patterns
Model View Presenter
Jean-Paul Boodhoo
Code download available at: DesignPatterns2006_08.exe (4423 KB)
Following the MVP Making the First Test Pass Filling the DropDownList Implementing the View Interface What's Next?
As UI-creation technologies such as ASP.NET and Windows® Forms become more and more powerful, it's common practice to let the UI layer do more than it should. Without a clear separation of responsibilities, the UI layer can often become a catch-all for logic that really belongs in other layers of the application. One design pattern, the Model View Presenter (MVP) pattern, is especially well suited to solving this problem. In order to illustrate my point, I will build a display screen that follows the MVP pattern for customers in the Northwind database.
Why is it bad to have lots of logic in the UI layer? The code in the UI layer of an application is very difficult to test without either running the application manually or maintaining ugly UI runner scripts that automate the execution of UI components. While this is a big problem in itself, an even bigger problem is the reams of code that are duplicated between common views in an application. It can often be hard to see good candidates for refactoring when the logic to perform a specific business function is copied among different pieces in the UI layer. The MVP design pattern makes it much easier to factor logic and code out of the UI layer for more streamlined, reusable code that's easier to test.
Figure 1 shows the main layers that make up the sample application. Notice that there are separate packages for UI and presentation. You might have expected them to be the same, but actually the UI layer of a project should consist only of the various UI elements—forms and controls. In a Web Forms project this is typically a collection of ASP.NET Web Forms, user controls, and server controls. In Windows Forms, it is a collection of Windows Forms, user controls, and third-party libraries. This extra layer is what keeps the display and the logic separate. In the presentation layer you have the objects that actually implement the behavior for the UI—things like validation display, collection input from the UI, and so forth.
Figure 1** Application Architecture **
Following the MVP
As you can see in Figure 2 , the UI for this project is pretty standard. When the page loads, the screen will display a dropdown box filled with all of the customers in the Northwind database. If you select a customer from the dropdown list, the page will update to display the information for that customer. By following the MVP design pattern you can factor behaviors out of the UI and into their own classes. Figure 3 shows a class diagram that indicates the association between the different classes that are involved.
Figure 2** Customer Information **
It's important to note that the presenter has no knowledge of the actual UI layer of the application. It knows it can talk to an interface, but it does not know or care what the implementation of that interface is. This promotes reuse of presenters between disparate UI technologies.
I am going to use Test Driven Development (TDD) to build the functionality of the customer screen. Figure 4 shows the details for the first test I will use to describe the behavior I expect to observe on page load. TDD lets me focus on one problem at a time, write just enough code to make the test pass, and then carry on. In this test I am making use of a mock object framework called NMock2 that allows me to build mock implementations of interfaces.
Figure 4 The First Test
Figure 3** MVP Class Diagram **
In my MVP implementation, I have decided that the presenter is going to take as a dependency the view it is going to work with. It is always good to create objects in a state that enables them to do their work immediately. In this application, the presentation layer is dependent on the service layer to actually invoke the domain functionality. Because of this requirement it also makes sense to construct a presenter with an interface to a service class that it can talk to. This ensures that once a presenter is constructed, it is ready to do all of the work it needs to do. I start off by creating two specific mocks: one for the service layer and one for the view that the presenter will work with.
Why mocks? A rule of unit testing is to isolate the test as much as possible to focus on one specific object. In this test I am only interested in the expected behavior of the presenter. At this point I don't care about the actual implementation of the view interface or service interface; I trust the contracts defined by those interfaces and set the mocks to behave accordingly. This ensures that I focus my test solely around the behavior I expect of the presenter, not of any of its dependencies. The behavior I expect the presenter to exhibit after its initialize method is invoked is as follows.
First, the presenter should make one call to the GetCustomerList method on the ICustomerTask service layer object (mocked in the test). Notice that with the use of NMock I can simulate behavior of the mock. In the case of the service layer, I want it to return a mock ILookupCollection to the presenter. Then, after the presenter retrieves the ILookupCollection from the service layer, it should invoke the collection's BindTo method and pass the method an implementation of an ILookupList. By using the NMockExpect.Once method I can be sure that the test will fail if the presenter does not call the method once and only once.
After writing that test I am in a completely non-compilable state. I'm going to do the simplest thing possible to get the test to pass.
Making the First Test Pass
One of the advantages of writing the test first is that I now have a blueprint (the test) I can follow to get the test to compile and eventually pass. The first test has two interfaces that do not yet exist. These interfaces are the first prerequisites for getting the code to compile correctly. I'll start with the code for IViewCustomerView:
This interface exposes one property that returns an ILookupList interface implementation. I don't yet have an ILookupList interface or even an implementer, for that matter. For the purpose of getting this test to pass I don't need an explicit implementor, so I can proceed to create the ILookupList interface:
At this point the ILookupList interface looks pretty useless. My goal is to get the test to compile and pass, and these interfaces satisfy the test's requirements. It's time to shift focus to the object that I'm actually testing—the ViewCustomerPresenter. This class does not exist yet, but looking at the test you can glean two important facts about it: it has a constructor that requires both a view and service implementation as dependencies, and it has a void Initialize method. The code in Figure 5 shows how to compile the test.
Figure 5 Compiling the Test
Remember that a presenter requires all of its dependencies in order to do its work meaningfully; this is why the view and service are passed in. I have not implemented the initialize method so if I run the test I get a NotImplementedException.
As mentioned already, I am not coding the presenter blindly; I already know, from looking at the test, what behavior the presenter should exhibit once the initialize method is called. The implementation of that behavior is as follows:
In the source code accompanying this article there is a complete implementation of the GetCustomerList method in the CustomerTask class (which implements the ICustomerTask interface). From the perspective of implementing and testing the presenter, though, I don't need to know whether there is a working implementation yet. It is this level of abstraction that allows me to plow through with the testing of the presenter class. The first test is now in a state that will compile and run. This proves that when the Initialize method on the presenter is called, it will interact with its dependencies in the manner that I specified in the test, and ultimately when the concrete implementations of those dependencies are injected into the presenter, I can be sure that the resulting view (the ASPX page) will be filled with a list of Customers.
Filling the DropDownList
So far I have been dealing mainly with interfaces to abstract the actual implementation details away, allowing the focus to be on the presenter. It is now time to build some of the plumbing that will ultimately allow the presenter to populate a list on a Web page in a way that can be tested. The key to making this work is the interaction that will occur in the BindTo method of the LookupCollection class. If you take a look at the implementation of the LookupCollection class in Figure 6 , you will notice that it implements the ILookupCollection interface. The source code for the article has the accompanying tests that were used to build up the functionality of the LookupCollection class.
Figure 6 The LookupCollection Class
The implementation of the BindTo method is of particular interest. Notice that in this method the collection iterates through its own private list of ILookupDTO implementations. An ILookupDTO is an interface that caters well to binding to comboboxes in the UI layer:
Figure 7 shows the code that tests the lookup collection's BindTo method, which will help explain the expected interaction between a LookupCollection and an ILookupList. The last line is of particular interest. In this test I expect that before attempting to add items to the list, the LookupCollection will invoke the Clear method on the ILookupList implementation. I then expect Add to be called on an ILookupList 10 times, and as an argument to the Add method, the LookupCollection will pass in an object that implements the ILookupDTO interface. To make this actually work with a control that lives in a Web project (such as a dropdown listbox) you will need to create an implementation of ILookupList that knows how to work with controls in a Web project.
Figure 7 A Test that Describes Behavior
The source code that accompanies this article contains a project named MVP.Web.Controls. This project contains any Web-specific controls or classes that I chose to create to complete the solution. Why did I place the code in this project and not in the APP_CODE directory or the Web project itself? Testability. Anything that lives in the Web project is difficult to test directly without either running the application manually or automating the UI using some sort of testing robot. The MVP pattern allows me to think at a higher level of abstraction and test implementations of the core interfaces (ILookupList and ILookupCollection) without manually running the application. I am going to add a new class, a WebLookupList control, to the Web.Controls project. Figure 8 shows the first test for this class.
Figure 8 First Test for WebLookupList Control
Some things stand out in the test that is shown in Figure 8 . The test project clearly needs a reference to the System.Web library so that it can instantiate DropDownList Web controls. Looking at the test, you should see that the WebLookupList class will implement the ILookupList interface. It is also going to take a ListControl as a dependency. Two of the most common ListControl implementations in the System.Web.UI.WebControls namespace are the DropDownList and the ListBox classes. A key feature of the test in Figure 8 is the fact that I am ensuring that a WebLookupList correctly updates the state of an actual Web ListControl to which it is delegating responsibility. Figure 9 shows the class diagram for the classes involved in the WebLookupList implementation. I can satisfy the requirements of the first test for the WebLookupList control with the code in Figure 10 .
Figure 10 WebLookupList Control
Figure 9** WebLookupList Class **
Remember, one of the keys to MVP is the separation of layers introduced by the creation of a view interface. The presenter doesn't know what implementation of a view, and respectively an ILookupList, it will be talking to; it just knows that it will be able to call any of the methods defined by those interfaces. Ultimately, the WebLookupList class is a class that wraps and delegates to an underlying ListControl (base class for some of the ListControls defined in the System.Web.UI.WebControls project). With that code now in place, I can compile and run the WebLookupList control test which should pass. I can add one more test for the WebLookupList that tests the actual behavior of the clear method:
Again I am testing that the WebLookupList class will actually change the state of the underlying ListControl (DropDownList) when its own methods are invoked. The WebLookupList is now feature complete for the purposes of populating a DropDownList in a Web Form. It is now time for me to wire everything together and get the Web page's dropdown filled with a list of customers.
Implementing the View Interface
Because I am building a Web Forms front end, it makes sense that the implementer for the IViewCustomerView interface would be a Web Form or a user control. For the purpose of this column, I'll make it a Web Form. The general appearance of the page has already been created, as you saw in Figure 2 . Now I need only to implement the view interface. Switching to the codebehind for the ViewCustomers.aspx page, I can add the following code, indicating that the page is required to implement the IViewCustomersView interface:
If you look at the code sample, you'll notice that the Web project and the Presentation are two completely different assemblies. Also, the Presentation project has no reference whatsoever to the Web.UI project, further maintaining the layer of separation. On the other hand, the Web.UI project has to have a reference to the Presentation project, as that is where the View interface and the presenter live.
By choosing to implement the IViewCustomerView interface, our Web page now has a responsibility to implement any methods or properties defined by that interface. Currently there is only one property on the IViewCustomerView interface and that is a getter that returns any implementation of an ILookupList interface. I added a reference to the Web.Controls project so that I can instantiate a WebLookupListControl. I did this because the WebLookupListControl implements the ILookupList interface and it knows how to delegate to actual WebControls that live in ASP.NET. Taking a look at the ASPX for the ViewCustomer page, you will see that the list of customers is simply an asp:DropDownList control:
With this already in place, I can quickly continue to implement the code required to satisfy the implementation of the IViewCustomerView interface:
I now need to invoke the Initialize method on the presenter that will trigger it to actually do some work. To do that, the view needs to be able to instantiate the presenter so that methods on it can be invoked. If you look back to the presenter, you'll remember that it requires both a view and a service that it will work with. The ICustomerTask interface represents an interface that lives in the service layer of the application. Service layers are typically responsible for orchestrating the interaction between domain objects and converting the results of those interactions into Data Transfer Objects (DTOs) that are then passed from the service layer to the presentation layer and then to the UI layer. There is a problem, however—I have stipulated that the presenter needs to be constructed with both the view and service implementations.
The actual instantiation of the presenter is going to take place in the codebehind for the Web page. This is a problem, because the UI project has no reference to the service layer project. The presentation project does, however, have a reference to the service layer project. This allows me to solve the problem by adding an overloaded constructor to the ViewCustomerPresenterClass:
This new constructor satisfies the presenter's requirement for implementations of both the view and the service, while also maintaining the separation of the UI layer from the service layer. It is now fairly trivial to finish off the code for the codebehind:
Notice the key to the instantiation of the presenter is the fact that I am making use of the newly created overload for the constructor, and the Web Form passes itself in as an object that implements the view interface!
With the code for the codebehind implemented, I can now build and run the application. The DropDownList on the Web page is now filled with a list of customer names without the need for any databinding code in the codebehind. Plus, scores of tests have been run on all the pieces that ultimately work together, ensuring that the presentation layer architecture will behave as expected.
I'm going to wrap up my discussion of MVP by showing what is required to display customer information for a customer selected in the DropDownList. Once again, I start by writing a test that describes the behavior I hope to observe (see Figure 11 ).
Figure 11 One Last Test
As before, I am taking advantage of the NMock library to create mocks of the task and view interfaces. This particular test verifies the behavior of the presenter by asking the service layer for a DTO representing a particular customer. Once the presenter retrieves the DTO from the service layer, it will update properties on the view directly, thus eliminating the need for the view to have any knowledge of how to correctly display the information from the object. For brevity I am not going to discuss the implementation of the SelectedItem property on the WebLookupList control; instead I will leave it to you to examine the source code to see the implementation details. What this test really demonstrates is the interaction that occurs between the presenter and the view once the presenter retrieves a CustomerDTO from the service layer. If I attempt to run the test now, I will be in a big failure state as a lot of the properties don't yet exist on the view interface. So I'll go ahead and add the necessary members to the IViewCustomerView interface, as you see in Figure 12 .
Figure 12 Completing the IVewCustomerView Interface
Immediately after adding these interface members, my Web Form complains because it is no longer fulfilling the contract of the interface, so I have to go back to the codebehind for my Web Form and implement the remaining members. As stated before, the entire markup for the Web page has already been created, as have the table cells which have been marked with the "runat=server" attribute and are named according to the information that should be displayed in them. This makes the resulting code to implement the interface members very trivial:
With the setter properties implemented, there is just one thing left to do. I need a way to tell the presenter to display the information for the selected customer. Looking back at the test, you can see that the implementation of this behavior will live in the DisplayCustomerDetails method on the presenter. This method will not, however, take any arguments. When invoked, the presenter will turn back around to the view, pull from it any information it needs (which it will retrieve by using the ILookupList), and then use that information to retrieve the details about the customer in question. All that I need to do from a UI perspective is set the AutoPostBack property of the DropDownList to true, and I also need to add the following event handler hookup code to the OnInit method of the page:
This event handler ensures that whenever a new customer is selected in the dropdown, the view will ask the presenter to display the details for that customer.
It is important to note that this is typical behavior. When a view asks a presenter to do something, it asks without giving any specific details, and it is up to the presenter to return to the view and get any information it needs using the view interface. Figure 13 shows the code required to implement the required behavior in the presenter.
Figure 13 Completing the Presenter
Hopefully you now see the value of adding the presenter layer. It is the presenter's responsibility to attempt to retrieve an ID for a customer for whom it needs to display details. This is code that would normally have been performed in the codebehind, but is now inside a class that I can fully test and exercise outside of any presentation-layer technology.
In the event that the presenter can retrieve a valid customer ID from the view, it turns to the service layer and asks for a DTO that represents the details for the customer. Once the presenter has the DTO in hand, it updates the view with the information contained in the DTO. A key point to note is the simplicity of the view interface; aside from the ILookupList interface, the view interface consists entirely of string DataTypes. It is ultimately the responsibility of the presenter to correctly convert and format the information retrieved from the DTO so that it can actually be handed to the view as a string. Although not demonstrated in this example, the presenter would also be responsible for reading information from the view and converting it to the necessary types that the service layer would expect.
With all the pieces in place I can now run the application. When the page first loads, I get a list of customers and the first customer appears (not selected) in the DropDownList. If I select a customer, a postback occurs, the interaction between the view and the presenter takes place, and the Web page is updated with the related customer information.
What's Next?
The Model View Presenter design pattern is really just a fresh take on the Model View Controller pattern that many developers are already familiar with; the key distinction is that MVP truly separates the UI from the domain/service layer of the application. Although this example was fairly simple from a requirements perspective, it should help you abstract the interaction between a UI and the other layers of your applications. Also, you should now see ways that you can use these layers of indirection to make your application more testable with automation. As you delve deeper into the MVP pattern, I hope you'll find other ways to pull as much formatting and conditional logic out of your codebehinds and place them into testable view/presenter interaction models.
Send your questions and comments to [email protected] .
Jean-Paul Boodhoo is a senior .NET delivery expert for ThoughtWorks where he is involved in the delivery of enterprise-scale applications that utilize the .NET Framework and agile methods. He frequently delivers presentations on harnessing the power of .NET utilizing test-driven development. Jean-Paul can be reached at [email protected] or at www.jpboodhoo.com/blog .
Additional resources
We've updated our privacy policy. Click here to review the details. Tap here to review the details.
Activate your 30 day free trial to unlock unlimited reading.
Design pattern-presentation


You are reading a preview.
Activate your 30 day free trial to continue reading.

Check these out next

Download to read offline
Recommended

More Related Content
Slideshows for you (20).

Viewers also liked (13)

Similar to Design pattern-presentation (20)

More from Rana Muhammad Asif (8)

- 1. Professional Practices Course Instructor : DR. Masroor Ahmed Bhatti Design Pattern Introduction Singleton, Observer & Factory Design Pattern.
- 2. Group Members I. Syed Danish Abbas BSCS 11-37 II. Ahsan Rasheed BSCS 11-39 III. Bilal Ejaz BSCS 11-52
- 3. Agenda Introduction to Design Pattern i. What is a Design Pattern? ii. Why study Design Pattern? iii. The Gang of Four (GOF). Singleton Design Pattern Observer Design Pattern Factory Design Pattern
- 4. What is a Design Pattern ? 1. A problem that someone has already solved. 2. A model or design to use as a guide. 3. More formally: “A proven solution to a common problem in a specified context." Real World Examples: i. Blueprint for a house ii. Manufacturing
- 5. Why Study Design Patterns? 1. Provides software developers a toolkit for handling problems that have already been solved. 2. Provides a vocabulary that can be used amongst software developers (The Pattern Name itself helps establish a vocabulary). 3. Helps you think about how to solve a software problem.
- 6. The Gang of Four Defines a Catalog of different design patterns. Three different types : I. Creational – “Creating objects in a manner suitable for the situation” II. Structural – “Ease the design by identifying a simple way to realize relationships between entities” III. Behavioral – “Common communication patterns between objects”
- 7. The Gang of Four: 1. Creational 3. Behavioral Abstract Factory Chain of Responsibility Builder Command Factory Method Interpreter Prototype Iterator Singleton Mediator 2. Structural Memento Adapter Observer Bridge State Composite Strategy Decorator Template Method Façade Visitor Flyweight Proxy Patterns in Red we will discuss in this presentation !!
- 8. Singleton Pattern (Creational)
- 9. Singleton Pattern Intent : Ensure a class has only one instance and provide a global point of access to it. Problem : How can we guarantee that one and only one instance of a class can be created? Solution : Define a class with a private constructor. The class constructs a single instance of itself. Supply a static method that returns a reference to the single instance.
- 10. Singleton: Basic Structure Singleton - instance: Singleton - Singleton(); + getInstance(): Singleton
- 11. Singleton sequence diagram
- 12. Singleton Participants 1. Singleton a) Defines an Instance operation that lets clients access its unique instance. Instance is a class operation (static method). b) May be responsible for creating its own unique instance 2. Client a) Accesses a Singleton instance solely through the Singleton’s Instance() method.
- 13. Singleton – Example 1) A status bar ….It could be implemented as a Singleton object, allowing only one instance and a focal point for updates. 2) One file system, one window manager, one printer spooler, one Test engine, one Input/output socket, Windows Registry etc.
- 14. Singleton: Basic Implementation Class Singleton { private static Singleton unique Instance = null; private Singleton( ) { .. } // private constructor public static Singleton getInstance( ) { if (uniqueInstance == null) uniqueInstance = new Singleton(); // call constructor return uniqueInstance; } }
- 15. Case Study We want to create a remote connection to a server / database system and assure that only one connection is present. . Apply Singleton pattern
- 16. Implementation : RemoteConnection Class RemoteConnection{ private static RemoteConnetion remoteConn; private RemoteConnection(){…} //private Constructor public static RemoteConnection getInstance(){ if( remoteConn == null ){ remoteConn = new RemoteConnection(); } return remoteConn; } }
- 17. Lazy Instantiation 1) Objects are only created when it is needed. 2) Helps control that we’ve created the Singleton just once. 3) If it is resource intensive to set up, we want to do it once.
- 18. Singleton Consequences: I. Controlled access to sole instance facilitates strict control over when and how the clients access it. II. The singleton patter is improvement over global variables. III. It is easy to configure an instance of the application that extends the functionality of singleton at run-time. IV. More flexible than class operations.
- 19. Singleton Limitations: 1) The main limitation of the singleton pattern is that is permits the creation of only one instance of the class, while most practical applications require multiple instances to be initialized. 2) Furthermore, in case of singleton, the system threads fight to access the single instance thereby degrading the performance of the applications.
- 20. Observer Pattern (Behavioral)
- 21. Observer Pattern (Behavioral) Intent : Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Also Known As : Dependents, Publish-Subscribe, Delegation Event Model. Problem : You need to notify a varying list of objects that an event has occurred. Solution : Delegate the responsibility for monitoring an event to a central object.
- 22. Basic Structure
- 23. Participants in structure Subject (interface): • Store the list of attached observers and provide operations for adding and removing the observer objects. • Expose an operation to notify all the attached observers Observer (interface): • Defines an interface for updating mechanism. ConcreteSubject: Get the update either from an external source or from any of the attached observer and notify the attached observers in case of change state. ConcreteObserver: • Maintains a reference to a ConcreteSubject object. • Stores state that should stay consistent with the subject's. • Implements the Observer updating interface to keep its state consistent with the subject's
- 24. Applying the Observer Step 1 : Make the Observers behave in the same way. Step 2 : Have the observers register themselves. Step 3 : Notify the observers when the event occurs. Step 4 : Get the information from the observable.
- 25. A case study… In a university….when a student changes his address…pass this information to: a) Exams department b) Transport department. What's the solution?
- 26. Applying observer to case study
- 27. Implementation: Observer interface public interface myObserver { public void update(Student s); }
- 28. Implementation: ExamDept class ExamDept implements myObserver { public void update(Student s){ System.out.println("Student Updated in Exam Dept"); System.out.println("New Address: "+ s.getAddress()); } }
- 29. Implementation: TransportDept class TransportDept implements myObserver { public void update(Student s) { System.out.println("Student Updated in TD"); System.out.println("New Address: "+s.getAddress()); } }
- 30. Implementation: Student class Student{ private String address; private Vector myObs; public Student(){ myObs = new Vector(); address = "Rawalpindi"; } public void register( myObserver obs ){ myObs.addElement ( obs ); } public void unRegister (myObserver obs){ myObs.remove (obs); } public void notifyObs (){ Enumeration e = myObs.elements(); while( e.hasMoreElements ()) { ((myObserver) e.nextElement ()).update(this); } } public void changeAddress (){ address = "Islamabad"; notifyObs(); } }
- 31. Implementation: Main class Main{ public static void main(String[]args){ Student s = new Student(); TransportDept td = new TransportDept(); ExamDept ed = new ExamDept(); System.out.println("Present Address:" + s.getAddress()); s.register (td); s.register (ed); s.changeAddress (); System.out.println("******Unregister Exam Dept*******"); s.unRegister (ed); s.changeAddress (); }}
- 32. Real Life Example Auctions: “Auctions demonstrate this pattern. Each bidder possesses a numbered paddle that is used to indicate a bid. The auctioneer starts the bidding, and "observes" when a paddle is raised to accept the bid. The acceptance of the bid changes the bid price which is broadcast to all of the bidders in the form of a new bid”
- 33. Pros & Cons Pros : i. Decoupling of subject and observer, each can be extended and reused individually. ii. Dynamic addition and removal of observers at runtime. iii. Subject broadcasts notification automatically to all interested objects, no matter how many or which kind of observers are registered. Cons : i. May result in many notifications the observers are not interested in ii. Potentially difficult for the observers to figure out the specific state change of the subject.
- 34. Factory Pattern (Creational)
- 35. Factory- Creational Pattern Intent: “Define an interface for creating an object, but let subclasses decide which class to instantiate” Also Known as Virtual Constructor.
- 36. Problem: “A framework needs to standardize the architectural model for a range of applications, but allow for individual applications to define their own domain objects and provide for their instantiation”
- 37. Solution: Factory Method Pattern offer a solution. It encapsulates the knowledge of which Document subclass to create and moves this knowledge out of the framework. Application subclasses redefine an abstract CreateDocument( ) on Application to return an appropriate Document subclass. Once an application subclass is instantiated , It can then instantiate application – specific Documents without knowing their Class , We call CreateDocument( ) a Factory Method because it is responsible for manufacturing an object.
- 38. Structure
- 39. Participants: Product( IHttpHandler) . Defines the interface of objects the factory method creates. ConcreteProduct ( ASP.SamplePage_aspx ) . Implements the Product Interface. Creator ( IHttpHandlerFactory ) . Declares the factory method and may provide a default implementation for it. . It returns an object of type Product. ConcreteCreator( PageHandlerFactory ) . Overrides the factory method to return an instance of ConcreteProduct.
- 40. Implementation: Two major varieties: 1. Abstract Creator class with no default implementation 2. Concrete Creator with default implementation. Solutions: 1. Parameterized Methods 2. Templates
- 41. Parameterized Factory Method: class Creator { public: virtual Product* Create( ProductID id ) { if (id == P1) return new MyProduct ; if (id == P2) return new YourProduct; // other products ... return 0; }}; // You can subclass the Creator to handle more IDs Product* MyCreator::Create(ProductID id) { if (id == P3) return new TheirProduct; // Handle other IDs return this->Creator::Create(id); };
- 42. Templatized Factory Methods: class Creator { public: Creator() { // You cannot call the factory method here (why?) // Use lazy initialization instead } virtual Product* CreateProduct() = 0; }; template <class T> class StandardCreator: public Creator { public: virtual Product* CreateProduct() { return new T; }} // In the Client StandardCreator<MyProduct> myCreator
- 43. Consequences: I. The code deals with only with the product interface, therefore it can work with any user defined Concrete Product classes (decoupling subclass details from client classes). II. New concrete classes can be added without recompiling the existing code. III. It may lead to many subclasses if the product objects requires one or more additional objects. (Parallel class hierarchy)
- 44. Known Uses: I. It is a very pervasive pattern. II. It is used in several places in the Java API. For example, URLConnection has a method getContent that returns the content as an appropriate object (html, gif etc.) III. FCL ( .Net Framework Class Library) is no exception to the use of Factory Method Pattern. For example, it is used in Systems.Collections.IEnumerable, System.Net.WebRequest, System.Security.Cryptography
- 45. Real Life Example: Hotel: “One good example for the Factory Method is the Hotel. When Check in, the person gets the key from the front desk where he can be looked up as the ‘room’ factory. Now if he wants to make a phone call to some outside office, he will contact the front desk to make the connection to that call which means the front desk is acting as an interface.”
- 46. But….. This presentation could not be completed without… The sources of information: 1. http://www.dofactory.com/Patterns/PatternObserver.aspx 2. http://www.vincehuston.org/dp/observer.html 3. http://en.wikipedia.org/wiki/Design_pattern 4. http://sourcemaking.com/design_patterns 5. Design Patterns: Elements of Reusable Object-oriented Software, by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, 1995 – “Gang of Four”. 6. Design Patterns in Ruby – Russ Olsen 7. Head First Design Patterns – Elisabeth Freeman, Eric Freeman, Bert Bates and Kathy Sierra 8. Special Thanks to Dr. Masroor Bhatti for providing us the chance to speak on Design Patterns.
- 47. If(Questions) { Ask; } else { Thank you; }
Share Clipboard
Public clipboards featuring this slide, select another clipboard.
Looks like you’ve clipped this slide to already.
You just clipped your first slide!
Create a clipboard
Get slideshare without ads, special offer to slideshare readers, just for you: free 60-day trial to the world’s largest digital library..
The SlideShare family just got bigger. Enjoy access to millions of ebooks, audiobooks, magazines, and more from Scribd.

You have now unlocked unlimited access to 20M+ documents!
Unlimited Reading
Learn faster and smarter from top experts
Unlimited Downloading
Download to take your learnings offline and on the go
Instant access to millions of ebooks, audiobooks, magazines, podcasts and more.
Read and listen offline with any device.
Free access to premium services like Tuneln, Mubi and more.
Help us keep SlideShare free
It appears that you have an ad-blocker running. By whitelisting SlideShare on your ad-blocker, you are supporting our community of content creators.
We've updated our privacy policy.
We’ve updated our privacy policy so that we are compliant with changing global privacy regulations and to provide you with insight into the limited ways in which we use your data.
You can read the details below. By accepting, you agree to the updated privacy policy.

- Latest Articles
- Top Articles
- Posting/Update Guidelines
- Article Help Forum

- View Unanswered Questions
- View All Questions
- View C# questions
- View Python questions
- View Javascript questions
- View C++ questions
- View Java questions
- CodeProject.AI Server
- All Message Boards...
- Running a Business
- Sales / Marketing
- Collaboration / Beta Testing
- Work Issues
- Design and Architecture
- Artificial Intelligence
- Internet of Things
- ATL / WTL / STL
- Managed C++/CLI
- Objective-C and Swift
- System Admin
- Hosting and Servers
- Linux Programming
- .NET (Core and Framework)
- Visual Basic
- Web Development
- Site Bugs / Suggestions
- Spam and Abuse Watch
- Competitions
- The Insider Newsletter
- The Daily Build Newsletter
- Newsletter archive
- CodeProject Stuff
- Most Valuable Professionals
- The Lounge
- The CodeProject Blog
- Where I Am: Member Photos
- The Insider News
- The Weird & The Wonderful
- What is 'CodeProject'?
- General FAQ
- Ask a Question
- Bugs and Suggestions

Presentation Model in Action

- Download source - 109.26 KB
Introduction
The Model-View-Controller (MVC) is the famous design pattern that separates the presentation and the domain/data access. Further more MVC also splits presentation logic into view and controller.
Presentation Model and Model View Presenter (MVP) are variations on model-view-controller (MVC) design pattern where the controller becomes Presentation Model and Presenter and has a different way to organize state, logic and references.
Presentation Model Key Features
- State is in the presentation model
- Logic is in the presentation model
- View observes the model and updates accordingly
- The view “knows” about the presentation model
- The presentation model does not “know” about the view
Model View Presenter has two flavors, named Supervising Controller and Passive View . They share the same key features.
Model View Presenter Key Features
- State is in the view
- Logic is in the Presenter
- Presenter observes the view
- Presenter updates the view
- Presenter ‘knows’ about the view
- View does not ‘know’ about the Presenter
Presentation Model is a pattern that pulls presentation behavior from a view. It has a centralized place to store state/data and centralized event source which is completely independent to the views used for display.
In real life projects, I prefer using the Presentation Model. This article is going to show the design journey of designing a use case of managing the Customer business entity and shows how the Presentation Model fits into ASP.NET Web site, Windows Form application and WPF application.
Let’s start with analyzing the requirements of a fictional business entity, Customer management application.
Requirement Analysis
Many business management processes can be abstracted as the following stories:
- User searches business entities
- User views the list of entities
- User selects an entity from the list
- User views the details of the selected entity
- User manipulates the selected entity, e.g. modify, delete etc.
Our story is about to manage Customer, the sample business entity. The use case can be described as below.
Use Case Name
Search and view customer information
Users search customers and view details of selected customer.
Pre-Conditions
User launches the application
Event Flows
- System displays all customers in a list and number of customers
- User searches customers by typing the search text
- System matches the search text with customer first name, last name and address If the search text is empty, system displays all customers
- System displays the customer list that matches the search text
- System displays the number of customers based on the search result
- User selects a customer
- System displays the details of the selected customer
- User can repeat the search
Design Considerations
The application can be designed as an ASP.NET Web site, a Windows Form application or a WPF application. This article will show all three application forms using the Presentation Model. To begin the design, first have a look at some user interface options on the Web site.
On a Web site, usually there are three options to implement this customer management.
Option 1: List Page and Popup Detail Page
This option is to display the customer list with a hyperlink on each row. When the hyperlink is clicked , a new popup window shows up with customer details in it.
Option 2: List Page and Switch to Detail Page
While the first option is a commonly used pattern in many earlier Web applications, more recent Web applications show the details in the same window to avoid popup.
Option 3: List Page and Embedded Detail Page
Similar to Option 2, there won't be popup, further more this option does not hide the list while showing the details either. It shows the list and details together.
The user experience designer usually decides which option is to be used in final products. The decision is based on users’ feedback and UI layout and look and feel designs.
The decision could be changed in the middle of the project. E.g. initially option 1 was chosen. Then users reported they blocked popup, so it has to be option 2. Finally, since the layout and font make the screen have quite a big space, designer may come to ask if we can display the list and details at the same time. It then becomes option 3.
Architectural design should foresee the potential requirement changes and have minimum impacts on code in case of the changes. Another word is to say the code should be reusable as much as possible.
Good news is that we can use user controls. User control is a great technology to achieve reusability. It is known as application building blocks. It created a customer list user control and a customer details user control. All three options can be built upon them.
In option 1, a page hosts customer list user control. A popup page hosts customer details user control.
In option 2, a page hosts customer list user control and customer details user control. When a customer is selected, hide the customer list user control and show the customer details user control.
In option 3, a page hosts customer list user control and customer details user control. When a customer is selected, show the customer details user control. Sometimes it may need to scroll the screen to the top of the customer details area.
Good news again is that no matter how screen layout or window arrangement changes, the data model behind the scene is actually the same. It is a customer list and a selected customer.
We need a class to hold the customer list and a selected customer. If the customer list changed in case the user typed in search text, it sends out an event saying customer list changed. If user selected a customer, it sends out an event saying selected customer changed.
User controls connect to this class and pull the customer list or selected customer to data bind to UI elements, such as grid view or form view.
User controls also listen to the events this class sends out. If the customer list changed, re-bind the grid view. Or if the selected customer changed, re-bind the form view.
Very naturally, the Presentation Model pattern comes into the picture. The class described above is exactly the Presentation Model, we name it CustomerPresentationModel .
The CustomerPresentationModel class has properties to hold the customer list and selected customer data.
In order to send out an event, we can define a custom event handler. But since Windows Forms data bind and WPF data bind rely on INotifyPropertyChanged interface , we use this interface .
The CustomerPresentationModel class is a subclass of the generic Presentation Model class, PresentationModel<T> .
PresentationModel<T> class is a base class using generics. With this class, we can apply the Presentation Model design pattern to all kinds of business entities, such as Order, Products, etc. in the future.
For now, we will focus only on the CustomerPresentationModel and on using it to build three types of applications.
Build the ASP.NET Web Site
The steps to build the ASP.NET Web site are:
These are straight forward steps, but there are some points of interests.
ASP.NET Web site can be stateless meaning that objects are typically created and destroyed to serve each request. In this case, due to the fact that Presentation Model is accessed by multiple user controls, it is expected to be created at the beginning of the request and live until the end of the request. But while ASP.NET Framework provides application scope storage and session storage to store custom objects, unlike JSP, it does not have a request scope storage. So we will store the CustomerPresentationModel in the session.
Data Bind to the Presentation Model Instance
ASP.NET has a great declarative databinding model against plain .NET objects. It is done through the ASP.NET ObjectDataSource control which connects the data-bound controls such as the GridView , FormView , or DetailsView controls to objects.
ObjectDataSource exposes a TypeName property that specifies an object type (class name) for performing data operations. In our case it is the CustomerPresentationModel .
By default, ObjectDataSource will instantiate CustomerPresentationModel instance through a default constructor (no arguments), but we already have CustomerPresentationModel object in the session. Fortunately, we can handle the ObjectCreating event to assign CustomerPresentationModel object from session to the ObjectInstance property of ObjectDataSource .
When data-bound controls need data, ObjectDataSource calls into the CustomerPresentationModel instance’s method GetCustomerList (declared in the ObjectDataSource ’s SelectMethod property). That method should return any Object or IEnumerable list, collection, or array.
CustomerPresentationModel exposes the customer list and selected customer as properties of, not method, so here we need a little wrapping in order to work with the ObjectDataSource .
Listen to the Events
The user controls listen to Presentation Model’s events. The customer list user control is monitoring the “items changed” event to re-bind the grid view. The customer details user control is similarly monitoring the “selected item changed” event. This is not only to refresh the form view, but also to hide itself if the selected item in the CustomerPresentationModel is null .
In CustomerEdit.ascx.cs ,
Event driven makes option 2 and option 3 very easy to implement. In option 2, the logic is if there is no customer selected, show the list and hide the details. In option 3, no extra logic is needed.
When user searches the customer list, CustomerPresentationModel sends out event “items changed” event to notify customer list user control to refresh accordingly.
In Customer2.aspx.cs ,
The benefit of this event driven mechanism is that there potentially could be more than one user controls to be notified and refreshed. And it also provides a solution to synchronize state of different user controls.
Need for Dependency Injection Framework
Looking into the code of CustomerList.ascx.cs and CustomerEdit.ascx.cs , you can find repeated code, like:
If there is a Dependency Injection Framework, then the above code can be simplified to be something look like this:
I am looking for a light weight Dependency Injection Framework that can be used in a Web application.
Windows Forms Application
We have created the ASP.NET Web site. It’s time to create a Windows Forms application.
The steps used in the ASP.NET Web site apply here which includes:
In Windows Forms application, CustomPresentationModel can live as a singleton. The data binding is also nice and easy by creating BindingSource in Visual Studio.
But it is important to remember that the Windows Forms data binding is driven off of change notification. That means the Windows Forms will only update a user interface element when the data source notifies that the data has changed (by providing a notification event).
In our case, the data source is the CustomPresentationModel instance. When customer list is reloaded, it sends out two PropertyChanged events. One has changed property name of Items , the other one has changed property name of ItemCount .
The label bound to the ItemCount property updated automatically, but the grid does not seems to pick up Items changed event. Why?
In the case of simple property to property binding, the data source needs to provide property change notification by either providing a " PropertyName changed event for the property or by implementing the INotifyPropertyChanged interface .
When the data source is a list, the data source needs to provide the list change notification that is used to notify user interface elements when an item has been added, removed or deleted from the list via the IBindingList interface .
That is to say to be fully integrated with Windows Forms data binding, the rule is to implement the INotifyPropertyChanged interface on your business entity class and use the IBindingList interface for your business entity collections.
I like data binding, but am hesitating to do it to pollute my entities and entity collections. I would rather refresh the grid view by the code using an anonymous method.
Within the Composite UI Application Block , there are Work Items that act like a dependency injection container and Event Broker that provides a many-to-many, loosely coupled event system mechanism. This application block is a perfect platform to build applications using the Presentation Model pattern.
WPF Application
As expected, the steps again are the same as those have been used in the ASP.NET Web site and the Windows Forms application.
Here, CustomPresentationModel lives as a singleton the same way as in the Windows Forms application.
The list view bound to the customer list updates accordingly to the Items changed event. Besides this, there are some other great features in WPF data binding.
In WPF, we can directly connect to the objects without helper such as the ObjectDataSource in ASP.NET and BindingSource in Windows Forms. Usually I define the a static resource referencing the CustomPresentationModel instance.
It is also possible to bind data to UI element’s DataContext property and allow the child element to inherit the data source information and simplify the binding syntax. This is well demonstrated in the CustomerEdit.asmx user control where the top level grid’s DataContext was bound to the selected customer object. Elements inside the grid then bind to the customer object’s properties just using path.
Some thoughts on WPF. WPF is supposed to bring application "differentiated user experience" or " differentiated UI ". In our case, it is possible upon the “selected item” changed event, active storyboard or timeline that mimic 3D effects or page flip effect in the bottom area of our application.
What does differentiated UI mean to LOB applications? Probably not just flipping the pages. I am waiting to see how the WPF composite client application block will define that.
So far we have created using the Presentation Model in ASP.NET Web site, a Windows Forms application and a WPF application. Although the Customer class used here is fictional, the design practice of the Web site UI options actually was a true story. We did not realize the Presentation Model is in action until we found the following references later on.
- Karsten Lentzsch’s Desktop Patterns and Data Binding Presentation
- John Gossman’s blog about the M-V-VM pattern for developing WPF applications
- Dan Crevier’s excellent multi-part blog posts
- Martin Fowler’s Patterns of Enterprise Application Architecture
- Paul Williams's blog Presentation Patterns - Presentation Model
Looks like since the Presentation Model originated from Smalltalk, Java world, FLEX world as well as .NET world are experimenting and using this pattern. This encouraged us to keep exploring more on this track.
Microsoft Web Client Software Factory and Microsoft Smart Client Software Factory are using MVP pattern. There are several things that are not as good as the Presentation Model. E.g. every view, usually a user control requires a presenter class addition to existing code behind class / code beside class. I feel it increases code maintenance difficulties. Not as clear as the Presentation Model demonstrated above.
Microsoft Smart Client Software Factory is based on the Composite UI Application Block (CAB) which provides many great features, such as Dependency Injection (IoC) Framework, event broker. To build application using CAB and the Presentation Model is easy and fun.
In the WPF would, the WPF team has been prompting the Model-View-ViewModel pattern. Essentially Model-View-ViewModel is a Presentation Model. They are two labels for the same thing.
In the coming WPF composite client application block , it is very interesting to see how the patterns & practices team from Microsoft will use the Presentation Model pattern or MVP. How will the Dependency Injection work and how to extend the WPF command/event handling to AOP style?
As demonstrated in this article, the Presentation Model is proven to be an effective pattern in practice. Although ASP.NET, Windows Forms and WPF are total different technologies, they can share the same Presentation Model class. The pattern brings the value of decoupling data model and presentation. It indeed can also integrate with and take advantages of many .NET technologies, such as user control and data binding.
Hope you start to like the Presentation Model after reading this article, if not yet. To make it more convincing, I have another article showing how to use the Presentation Model in SharePoint .
- Feb 3, 2008: Added link to article Presentation Model in SharePoint
- Jan 31, 2008: First version
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Comments and Discussions
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

IMAGES
VIDEO
COMMENTS
Presentation Model is a pattern that pulls presentation behavior from a view. As such it's an alternative to to Supervising Controller and
Before we try a new design pattern, let's work out the basics. Our MVC Design. Model: We start with a MessageStore . It has a
As the name suggests these are applicable to only Presentation tier. Model View Controller (MVC) was the first pattern that was developed by
Model–view–presenter (MVP) is a derivation of the model–view–controller (MVC) architectural pattern, and is used mostly for building user interfaces.
What is Presentation Model design pattern? ... My mentor Martin Fowler describes it with those words: “Represent the state and behavior of the
The Remote Presentation Model Pattern. 1K views 6 years ago. Oracle Developers. Oracle Developers. 89.3K subscribers. Subscribe.
You probably have already heard about design patterns that could help in this case, especially those that separate the application logic from UI
In the presentation layer you have the objects that actually implement the behavior for the UI—things like validation display, collection input
Also Known As : Dependents, Publish-Subscribe, Delegation Event Model. Problem : You need to notify a varying list of objects that an event has occurred.
Presentation Model and Model View Presenter (MVP) are variations on model-view-controller (MVC) design pattern where the controller becomes