Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
When looking beyond the RAD (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called Model-View-Controller, Model-View-Presenter and Model-View-ViewModel. My question has three parts to it:
What issues do these patterns address? How are they similar? How are they different?
Model-View-Presenter
In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.
MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can find out more about both variants.
Two primary variations
Passive View: The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View.
Pro: maximum testability surface; clean separation of the View and Model
Con: more work (for example all the setter properties) as you are doing all the data binding yourself.
Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.
Pro: by leveraging data binding the amount of code is reduced.
Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.
Model-View-Controller
In the MVC, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:
Action in the View -> Call to Controller -> Controller Logic -> Controller returns the View.
One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.
Presentation Model
One other pattern to look at is the Presentation Model pattern. In this pattern, there is no Presenter. Instead, the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behavior for the view. This pattern is a very strong candidate for use in WPF applications and is also called Model-View-ViewModel.
There is a MSDN article about the Presentation Model and a section in the Composite Application Guidance for WPF (former Prism) about Separated Presentation Patterns
This is an oversimplification of the many variants of these design patterns, but this is how I like to think about the differences between the two.
MVC
https://i.stack.imgur.com/X3CAF.png
MVP
https://i.stack.imgur.com/Pa0iB.png
I blogged about this a while back, quoting on Todd Snyder's excellent post on the difference between the two:
Here are the key differences between the patterns: MVP Pattern View is more loosely coupled to the model. The presenter is responsible for binding the model to the view. Easier to unit test because interaction with the view is through an interface Usually view to presenter map one to one. Complex views may have multi presenters. MVC Pattern Controller are based on behaviors and can be shared across views Can be responsible for determining which view to display
It is the best explanation on the web I could find.
Here are illustrations which represent communication flow
https://i.stack.imgur.com/t2kzD.png
MVP is not necessarily a scenario where the View is in charge (see Taligent's MVP for example). I find it unfortunate that people are still preaching this as a pattern (View in charge) as opposed to an anti-pattern as it contradicts "It's just a view" (Pragmatic Programmer). "It's just a view" states that the final view shown to the user is a secondary concern of the application. Microsoft's MVP pattern renders re-use of Views much more difficult and conveniently excuses Microsoft's designer from encouraging bad practice.
To be perfectly frank, I think the underlying concerns of MVC hold true for any MVP implementation and the differences are almost entirely semantic. As long as you are following separation of concerns between the view (that displays the data), the controller (that initialises and controls user interaction) and the model (the underlying data and/or services)) then you are achieving the benefits of MVC. If you are achieving the benefits then who really cares whether your pattern is MVC, MVP or Supervising Controller? The only real pattern remains as MVC, the rest are just differing flavours of it.
Consider this highly exciting article that comprehensively lists a number of these differing implementations. You may note that they're all basically doing the same thing but slightly differently.
I personally think MVP has only been recently re-introduced as a catchy term to either reduce arguments between semantic bigots who argue whether something is truly MVC or not or to justify Microsofts Rapid Application Development tools. Neither of these reasons in my books justify its existence as a separate design pattern.
MVP: the view is in charge.
The view, in most cases, creates its presenter. The presenter will interact with the model and manipulate the view through an interface. The view will sometimes interact with the presenter, usually through some interface. This comes down to implementation; do you want the view to call methods on the presenter or do you want the view to have events the presenter listens to? It boils down to this: The view knows about the presenter. The view delegates to the presenter.
MVC: the controller is in charge.
The controller is created or accessed based on some event/request. The controller then creates the appropriate view and interacts with the model to further configure the view. It boils down to: the controller creates and manages the view; the view is slave to the controller. The view does not know about the controller.
https://i.stack.imgur.com/A7cSy.jpg
MVC (Model View Controller)
The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality. There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed. Note the one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller. The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.
MVP (Model View Presenter)
The input begins with the View, not the Presenter. There is a one-to-one mapping between the View and the associated Presenter. The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with. The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.
For more Reference
MVP
pattern, when the application loads for the first time , isn't the presenter is responsible to load the first view? Like for example when we load the facebook applicaiton, isn't the presenter responsible to load the login page?
There are many answers to the question, but I felt there is a need for some really simple answer clearly comparing the two. Here's the discussion I made up when a user searches for a movie name in an MVP and MVC app:
User: Click click …
View: Who’s that? [MVP|MVC]
User: I just clicked on the search button …
View: Ok, hold on a sec … . [MVP|MVC]
( View calling the Presenter|Controller … ) [MVP|MVC]
View: Hey Presenter|Controller, a User has just clicked on the search button, what shall I do? [MVP|MVC]
Presenter|Controller: Hey View, is there any search term on that page? [MVP|MVC]
View: Yes,… here it is … “piano” [MVP|MVC]
Presenter|Controller: Thanks View,… meanwhile I’m looking up the search term on the Model, please show him/her a progress bar [MVP|MVC]
( Presenter|Controller is calling the Model … ) [MVP|MVC]
Presenter|Controller: Hey Model, Do you have any match for this search term?: “piano” [MVP|MVC]
Model: Hey Presenter|Controller, let me check … [MVP|MVC]
( Model is making a query to the movie database … ) [MVP|MVC]
( After a while ... )
-------------- This is where MVP and MVC start to diverge ---------------
Model: I found a list for you, Presenter, here it is in JSON “[{"name":"Piano Teacher","year":2001},{"name":"Piano","year":1993}]” [MVP]
Model: There is some result available, Controller. I have created a field variable in my instance and filled it with the result. It's name is "searchResultsList" [MVC]
(Presenter|Controller thanks Model and gets back to the View) [MVP|MVC]
Presenter: Thanks for waiting View, I found a list of matching results for you and arranged them in a presentable format: ["Piano Teacher 2001","Piano 1993"]. Please show it to the user in a vertical list. Also please hide the progress bar now [MVP]
Controller: Thanks for waiting View, I have asked Model about your search query. It says it has found a list of matching results and stored them in a variable named "searchResultsList" inside its instance. You can get it from there. Also please hide the progress bar now [MVC]
View: Thank you very much Presenter [MVP]
View: Thank you "Controller" [MVC] (Now the View is questioning itself: How should I present the results I get from the Model to the user? Should the production year of the movie come first or last...? Should it be in a vertical or horizontal list? ...)
In case you're interested, I have been writing a series of articles dealing with app architectural patterns (MVC, MVP, MVVP, clean architecture, ...) accompanied by a Github repo here. Even though the sample is written for android, the underlying principles can be applied to any medium.
Model-View-Controller
MVC is a pattern for the architecture of a software application. It separate the application logic into three separate parts, promoting modularity and ease of collaboration and reuse. It also makes applications more flexible and welcoming to iterations.It separates an application into the following components:
Models for handling data and business logic
Controllers for handling the user interface and application
Views for handling graphical user interface objects and presentation
To make this a little more clear, let's imagine a simple shopping list app. All we want is a list of the name, quantity and price of each item we need to buy this week. Below we'll describe how we could implement some of this functionality using MVC.
https://i.stack.imgur.com/xjBSZ.png
Model-View-Presenter
The model is the data that will be displayed in the view (user interface).
The view is an interface that displays data (the model) and routes user commands (events) to the Presenter to act upon that data. The view usually has a reference to its Presenter.
The Presenter is the “middle-man” (played by the controller in MVC) and has references to both, view and model. Please note that the word “Model” is misleading. It should rather be business logic that retrieves or manipulates a Model. For instance: If you have a database storing User in a database table and your View wants to display a list of users, then the Presenter would have a reference to your database business logic (like a DAO) from where the Presenter will query a list of Users.
If you want to see a sample with simple implementation please check this GitHub post
https://i.stack.imgur.com/QwKUW.png
What is the difference between MVC and MVP patterns?
MVC Pattern
Controller are based on behaviors and can be shared across views
Can be responsible for determining which view to display (Front Controller Pattern)
MVP Pattern
View is more loosely coupled to the model. The presenter is responsible for binding the model to the view.
Easier to unit test because interaction with the view is through an interface
Usually view to presenter map one to one. Complex views may have multi presenters.
MVP = Model-View-Presenter
MVC = Model-View-Controller Both presentation patterns. They separate the dependencies between a Model (think Domain objects), your screen/web page (the View), and how your UI is supposed to behave (Presenter/Controller) They are fairly similar in concept, folks initialize the Presenter/Controller differently depending on taste. A great article on the differences is here. Most notable is that MVC pattern has the Model updating the View.
Both presentation patterns. They separate the dependencies between a Model (think Domain objects), your screen/web page (the View), and how your UI is supposed to behave (Presenter/Controller)
They are fairly similar in concept, folks initialize the Presenter/Controller differently depending on taste.
A great article on the differences is here. Most notable is that MVC pattern has the Model updating the View.
Also worth remembering is that there are different types of MVPs as well. Fowler has broken the pattern into two - Passive View and Supervising Controller.
When using Passive View, your View typically implement a fine-grained interface with properties mapping more or less directly to the underlaying UI widget. For instance, you might have a ICustomerView with properties like Name and Address.
Your implementation might look something like this:
public class CustomerView : ICustomerView
{
public string Name
{
get { return txtName.Text; }
set { txtName.Text = value; }
}
}
Your Presenter class will talk to the model and "map" it to the view. This approach is called the "Passive View". The benefit is that the view is easy to test, and it is easier to move between UI platforms (Web, Windows/XAML, etc.). The disadvantage is that you can't leverage things like databinding (which is really powerful in frameworks like WPF and Silverlight).
The second flavor of MVP is the Supervising Controller. In that case your View might have a property called Customer, which then again is databound to the UI widgets. You don't have to think about synchronizing and micro-manage the view, and the Supervising Controller can step in and help when needed, for instance with compled interaction logic.
The third "flavor" of MVP (or someone would perhaps call it a separate pattern) is the Presentation Model (or sometimes referred to Model-View-ViewModel). Compared to the MVP you "merge" the M and the P into one class. You have your customer object which your UI widgets is data bound to, but you also have additional UI-spesific fields like "IsButtonEnabled", or "IsReadOnly", etc.
I think the best resource I've found to UI architecture is the series of blog posts done by Jeremy Miller over at The Build Your Own CAB Series Table of Contents. He covered all the flavors of MVP and showed C# code to implement them.
I have also blogged about the Model-View-ViewModel pattern in the context of Silverlight over at YouCard Re-visited: Implementing the ViewModel pattern.
Both of these frameworks aim to seperate concerns - for instance, interaction with a data source (model), application logic (or turning this data into useful information) (Controller/Presenter) and display code (View). In some cases the model can also be used to turn a data source into a higher level abstraction as well. A good example of this is the MVC Storefront project.
There is a discussion here regarding the differences between MVC vs MVP.
The distinction made is that in an MVC application traditionally has the view and the controller interact with the model, but not with each other.
MVP designs have the Presenter access the model and interact with the view.
Having said that, ASP.NET MVC is by these definitions an MVP framework because the Controller accesses the Model to populate the View which is meant to have no logic (just displays the variables provided by the Controller).
To perhaps get an idea of the ASP.NET MVC distinction from MVP, check out this MIX presentation by Scott Hanselman.
Both are patterns trying to separate presentation and business logic, decoupling business logic from UI aspects
Architecturally, MVP is Page Controller based approach where MVC is Front Controller based approach. That means that in MVP standard web form page life cycle is just enhanced by extracting the business logic from code behind. In other words, page is the one servicing http request. In other words, MVP IMHO is web form evolutionary type of enhancement. MVC on other hand changes completely the game because the request gets intercepted by controller class before page is loaded, the business logic is executed there and then at the end result of controller processing the data just dumped to the page ("view") In that sense, MVC looks (at least to me) a lot to Supervising Controller flavor of MVP enhanced with routing engine
Both of them enable TDD and have downsides and upsides.
Decision on how to choose one of them IMHO should be based on how much time one invested in ASP NET web form type of web development. If one would consider himself good in web forms, I would suggest MVP. If one would feel not so comfortable in things such as page life cycle etc MVC could be a way to go here.
Here's yet another blog post link giving a little bit more details on this topic
I have used both MVP and MVC and although we as developers tend to focus on the technical differences of both patterns the point for MVP in IMHO is much more related to ease of adoption than anything else.
If I’m working in a team that already as a good background on web forms development style it’s far easier to introduce MVP than MVC. I would say that MVP in this scenario is a quick win.
My experience tells me that moving a team from web forms to MVP and then from MVP to MVC is relatively easy; moving from web forms to MVC is more difficult.
I leave here a link to a series of articles a friend of mine has published about MVP and MVC.
http://www.qsoft.be/post/Building-the-MVP-StoreFront-Gutthrie-style.aspx
In MVP the view draws data from the presenter which draws and prepares/normalizes data from the model while in MVC the controller draws data from the model and set, by push in the view.
In MVP you can have a single view working with multiple types of presenters and a single presenter working with different multiple views.
MVP usually uses some sort of a binding framework, such as Microsoft WPF binding framework or various binding frameworks for HTML5 and Java.
In those frameworks, the UI/HTML5/XAML, is aware of what property of the presenter each UI element displays, so when you bind a view to a presenter, the view looks for the properties and knows how to draw data from them and how to set them when a value is changed in the UI by the user.
So, if for example, the model is a car, then the presenter is some sort of a car presenter, exposes the car properties (year, maker, seats, etc.) to the view. The view knows that the text field called 'car maker' needs to display the presenter Maker property.
You can then bind to the view many different types of presenter, all must have Maker property - it can be of a plane, train or what ever , the view doesn't care. The view draws data from the presenter - no matter which - as long as it implements an agreed interface.
This binding framework, if you strip it down, it's actually the controller :-)
And so, you can look on MVP as an evolution of MVC.
MVC is great, but the problem is that usually its controller per view. Controller A knows how to set fields of View A. If now, you want View A to display data of model B, you need Controller A to know model B, or you need Controller A to receive an object with an interface - which is like MVP only without the bindings, or you need to rewrite the UI set code in Controller B.
Conclusion - MVP and MVC are both decouple of UI patterns, but MVP usually uses a bindings framework which is MVC underneath. THUS MVP is at a higher architectural level than MVC and a wrapper pattern above of MVC.
My humble short view: MVP is for large scales, and MVC for tiny scales. With MVC, I sometime feel the V and the C may be seen a two sides of a single indivisible component rather directly bound to M, and one inevitably falls to this when going down‑to shorter scales, like UI controls and base widgets. At this level of granularity, MVP makes little sense. When one on the contrary go to larger scales, proper interface becomes more important, the same with unambiguous assignment of responsibilities, and here comes MVP.
On the other hand, this scale rule of a thumb, may weight very little when the platform characteristics favours some kind of relations between the components, like with the web, where it seems to be easier to implement MVC, more than MVP.
I think this image by Erwin Vandervalk (and the accompanying article) is the best explanation of MVC, MVP, and MVVM, their similarities, and their differences. The article does not show up in search engine results for queries on "MVC, MVP, and MVVM" because the title of the article does not contain the words "MVC" and "MVP"; but it is the best explanation, I think.
https://i.stack.imgur.com/Y82D3.png
(The article also matches what Uncle Bob Martin said in his one of his talks: that MVC was originally designed for the small UI components, not for the architecture of the system)
https://i.stack.imgur.com/aebJI.png
This talk droidcon NYC 2017 - Clean app design with Architecture Components clarifies it
https://i.stack.imgur.com/wPqMA.png
UIKit
MVC (Model-View-Controller)
In MVC, the Controller is the one in charge! The Controller is triggered or accessed based on some events/requests then, manages the Views.
Views in MVC are virtually stateless, the Controller is responsible for choosing which View to show.
E.g.: When the user clicks on the “Show MyProfile” button, the Controller is triggered. It communicates with the Model to get the appropriate data. Then, it shows a new View that resembles the profile page. The Controller may take the data from the Model and feed it directly to the View -as proposed in the above diagram- or let the View fetch the data from the Model itself.
MVP (Model-View-Presenter)
In MVP, the View is the one in charge! each View calls its Presenter or has some events that the Presenter listens to.
Views in MVP don’t implement any logic, the Presenter is responsible for implementing all the logic and communicates with the View using some sort of interface.
E.g.: When the user clicks the “Save” button, the event handler in the View delegates to the Presenter’s “OnSave” method. The Presenter will do the required logic and any needed communication with the Model then, calls back the View through its interface so that the View can display that the save has been completed.
MVC vs. MVP
MVC doesn’t put the View in charge, Views act as slaves that the Controller can manage and direct.
In MVC, Views are stateless contrary to Views in MVP where they are stateful and can change over time.
In MVP, Views have no logic and we should keep them dumb as possible. On the other hand, Views in MVC may have some sort of logic.
In MVP, the Presenter is decoupled from the View and talks to it through an interface. This allows mocking the View in unit tests.
In MVP, Views are completely isolated from the Model. However, in MVC, Views can communicate with the Model to keep it up with the most up-to-date data.
https://i.stack.imgur.com/Yttsn.png
The simplest answer is how the view interacts with the model. In MVP the view is updated by the presenter, which acts as as intermediary between the view and the model. The presenter takes the input from the view, which retrieves the data from the model and then performs any business logic required and then updates the view. In MVC the model updates the view directly rather than going back through the controller.
There is this nice video from Uncle Bob where he briefly explains MVC & MVP at the end.
IMO, MVP is an improved version of MVC where you basically separate the concern of what you're gonna show (the data) from how you're gonna show (the view). The presenter includes kinda the business logic of your UI, implicitly imposes what data should be presented and gives you a list of dumb view models. And when the time comes to show the data, you simply plug your view (probably includes the same id's) into your adapter and set the relevant view fields using those view models with a minimum amount of code being introduced (just using setters). Its main benefit is you can test your UI business logic against many/various views like showing items in a horizontal list or vertical list.
In MVC, we talk through interfaces (boundaries) to glue different layers. A controller is a plug-in to our architecture but it has no such a restriction to impose what to show. In that sense, MVP is kind of an MVC with a concept of views being pluggable to the controller over adapters.
I hope this helps better.
You forgot about Action-Domain-Responder (ADR).
As explained in some graphics above, there's a direct relation/link between the Model and the View in MVC. An action is performed on the Controller, which will execute an action on the Model. That action in the Model, will trigger a reaction in the View. The View, is always updated when the Model's state changes.
Some people keep forgetting, that MVC was created in the late 70", and that the Web was only created in late 80"/early 90". MVC wasn't originally created for the Web, but for Desktop applications instead, where the Controller, Model and View would co-exist together.
Because we use web frameworks (eg:. Laravel) that still use the same naming conventions (model-view-controller), we tend to think that it must be MVC, but it's actually something else.
Instead, have a look at Action-Domain-Responder. In ADR, the Controller gets an Action, which will perform an operation in the Model/Domain. So far, the same. The difference is, it then collects that operation's response/data, and pass it to a Responder (eg:. view()
) for rendering. When a new action is requested on the same component, the Controller is called again, and the cycle repeats itself. In ADR, there's no connection between the Model/Domain and the View (Reponser's response).
Note: Wikipedia states that "Each ADR action, however, is represented by separate classes or closures.". This is not necessarily true. Several Actions can be in the same Controller, and the pattern is still the same.
mvc adr model-view-controller action-domain-responder
In a few words,
In MVC, View has the UI part, which calls the controller which in turn calls the model & model in turn fires events back to view.
In MVP, View contains UI and calls the presenter for implementation part. The presenter calls the view directly for updates to the UI part. Model which contains business logic is called by the presenter and no interaction whatsoever with the view. So here presenter does most of the work :)
MVP
MVP stands for Model - View- Presenter. This came to a picture in early 2007 where Microsoft introduced Smart Client windows applications.
A presenter is acting as a supervisory role in MVP which binding View events and business logic from models.
View event binding will be implemented in the Presenter from a view interface.
The view is the initiator for user inputs and then delegates the events to the Presenter and the presenter handles event bindings and gets data from models.
Pros: The view is having only UI not any logics High level of testability
Cons: Bit complex and more work when implementing event bindings
MVC
MVC stands for Model-View-Controller. Controller is responsible for creating models and rendering views with binding models.
Controller is the initiator and it decides which view to render.
Pros: Emphasis on Single Responsibility Principle High level of testability
Cons: Sometimes too much workload for Controllers, if try to render multiple views in same controller.
Success story sharing
MVC
is often used by web-frameworks likeLaravel
, where the received URL requests (maybe made by users) are handled by theController
and the HTML generated by theView
is sent to the client -- So, theView
is a part of the backend and the user can never access it directly, and if you experience anywhere the opposite then consider that as an MVC-extension (or even violation). @Panzercrisis, This differs fromMVP
(like that used inAndroid
OS) whereactions route through the View to the Presenter
and user have direct access to theView
.