MVC, MVP, MVVM comparison and difference

Source: Internet
Author: User

MVC, MVP, and MVVM are all patterns used to solve the problem of interface rendering and logical code separation. Previously only a partial understanding of them, no in-depth research, for some of the concepts and differences are also smattering. Now, while looking at the information, and in combination with their own understanding, to talk about the three models of the idea of understanding, and their differences. Welcome you to shoot bricks.

Read the catalogue:

A. MVC, MVP, the need for the birth of MVVM?

Two. A typical coupling code

Three. Mvc mode

3.1 Active MVC

3.2 Passive MVC

3.3 The MVC framework in Web applications

3.4 MVC Summary

One, MVC, MVP, the need for the birth of MVVM?

What is the most basic thing in software? Yes, it's data. All the code we write is around the data. The business logic emerges around the change of data generation and modification. Around the display of data, there are different interface technologies.

Without well-designed code, it is often the case that the data layer (persistence layer) and the business Logic layer and interface code coupling are present.

ORM Frameworks, which decouple the coupling between business logic and data, business logic no longer cares about how the underlying data is stored and read. All the data presented to the business logic layer is a one-to-one object. and MVC, MVP, MMVM is used to solve the coupling between business logic and views.

Two, a typical coupling code
New SqlDataAdapter ("select * from Table1","server=.; Database=db;uid=sa;pwd=password"new DataSet ("ds1"); adapter. Fill (DS); This . Gridview1.datasource = ds;  This. Gridview1.databind ();}              

The above code contains both the data access and the page presentation. When the project is more complex, the code becomes very difficult to maintain and the hierarchy is not clear.

Third, the MVC pattern

The full name of MVC is the Model View controller, which is the abbreviation for the models-view-controller. MVC begins in the desktop program, M refers to the business model, v refers to the user interface, C is the controller, the purpose of using MVC is to separate m and v implementation code, so that the same program can use different representations

3.1 Active MVC

MVC's theoretical thinking corresponds to active MVC, where the initiative means that the model will proactively notify the view update. And we use the MVC framework, Struts, ASP. NET MVC, etc. are not active MVC (view updates are all done by the Controller)

Model

Used to encapsulate data related to the business logic of the application and how to handle the data. Changes to the data in the model are generally advertised through a refresh mechanism. To implement this mechanism, the views that are used to monitor this model must be registered in advance on this model, so that the view can understand the changes that have occurred on the data model.

View

The view layer is responsible for the presentation of the data. There is generally no logic on the program in the view. To implement the Refresh feature on the view, the view needs to access the data model it monitors, so you should subscribe to the model's events beforehand in the data it is monitoring.

Controller

The controller is a connector between M and V that controls the flow of the application. It handles the event and responds. An "event" includes the user's behavior and changes on the data model.

3.2 Passive MVC

is a process in passive MVC, Unlike active MVC, where view does not subscribe to the events of model data changes, waits for model to notify that the view needs to be updated according to the new data. In passive MVC, the controller is responsible for notifying the view, There are data changes that require a view to be updated.

in passive MVC, the difference with active MVC is that: 1, the model is not known to view and controller, it is only used by them 2, the controller uses the views, and notifies it to update the data display 3, the view is only when the controller notifies it to the model to fetch data when it does this (the view does not subscribe or Update of the monitoring model)

3.3. The MVC framework in Web applications

The MVC framework in the web is a passive MVC pattern, because in Web applications, because HTTP works together based on request and response, it does not immediately update the client view when the server-side model (data) changes. Updates only if the client requests or refreshes the page again.

is a typical MVC framework in which MVC is a request process.

3.4 MVC Summary

MVC Benefits

    • Because MVC separates the view layer and the business layer nicely, it has the following advantages
    • Low coupling resistance
    • Fast development speed
    • High maintainability
    • No control concept, no encapsulation of HTML, easy to understand
    • More similar to other platforms (Java, PHP). Easy access to Talent

The pitfalls of MVC use

1. The model is understood as an entity class, and in MVC the model should contain 2 parts, part of the business logic, and part of the data that provides the view display 2. Put the business logic all on the controller side

These two misunderstandings are essentially the role of the model of unknown cause.

The role of model in the MVC architecture is very important, and it should be the real implementation layer of the business logic. So the model is actually business model. The controller only plays a "bridge" role, it is responsible for the view request to the model, and then responsible for the model processing end of the message to notify the view. The controller is used to decouple the view and model, specifically to separate the UI from the logic (the interface is separated from the code).

Quoted Http://www.techopedia.com/definition/27454/model-mvc-aspnet

Techopedia explains Model (MVC)

The Model is the part of MVC which implements the domain logic. In simple terms, this logic is used to handle the data passed between the database and the user interface (UI).

The Model is known as domain object or domain entity. The domain objects is stored under the Models folder in ASP. The domain model represents the application perspective for the data to be handled whereas a view model are required to pro Duce the engine that generates the View.

This definition is written in the context of ASP.

The drawbacks of MVC

The perfect MVC application scenario should look like this:

There is a student Model, associated Studentlistview, Studenteditview. For Studentlistview, Student model provides Student collection data to display Studentlistview for Studenteditview, Student The model provides a single student data to show Studenteditview and respond to studenteditview save operations.

But this is only the perfect situation, the actual application, in the ListView, not only show student information, may also need this student historical results, family situation, teacher information. And these are not available in the student model. Perhaps we can expand the student model to extend the information that student model can provide, including performance information, which itself can be. However, if Student shows the view, this need only need additional information, another view just need additional family information, Student model is not a bit busy, you can know how many different view needs? And let the logic-side code change so constantly to fit the view side, okay?

Since the design of MVC is based on the model, and does not take into account the complexity of the view side, the problem is that model is difficult to meet the complex and changeable view-side changes. In contrast, MVP and MVVM are much better. They are all independent of presenter and ViewModel to correspond to each view.

Four. MVP mode

The idea of 4.1 MVP

4.2 UI Interface Interface

4.3 The bridge between Presenter--model and view

4.4 MVP's code structure and timing diagram

4.5 MVP Model Summary

Five. MVVM mode

Design idea of 5.1 MVVM pattern

5.2 MVVM Pattern Structure diagram

Six. MVC, MVP, and MVVM pattern Usage Scenario Summary

Four, MVP mode

MVP Mode is also a classic interface mode. The MVP's M represents model, V is view, and P is presenter. The complete code in the following example can be downloaded here: WINFORMMVP source You can also compare this article in the park Artech about the v-p interaction problem in MVP mode

The idea of 4.1 MVP

The MVP model seems to me to be a real sense of isolating the details and complexity of the view pattern. Why do you say this: because in other modes v represents the UI interface, it is an HTML page, a XAML file, or a WinForm interface. But in MVP mode, V represents an interface, an interface that abstracts the UI interface. interface means that any interface that implements the interface can reuse existing presenter and model code.

4.2 UI Interface Interface

To understand the MVP well, there is the ability to interface the UI interface. Look at the following interface, the red flag of the user control abstraction, you can get the following interface

Interface Iuseradd {        event EventHandler useraddevent;       setset;}}     

The 2 input boxes in the interface are abstracted into two properties of username and Userage. The Click event of the Save button is abstracted into the event useraddevent. The code that implements the interface in WinForm is as follows:

PublicPartialClassUseradd:usercontrol, Iuseradd {PublicEventEventHandler useraddevent;PublicStringUserName {set {This.txbName.Text =Value }get {ReturnThis. Txbname.text; } }public string Userage { set {this.txbage.text = get {return this.txbage.text; }} public UserAdd () {InitializeComponent ();} private void btnAdd_Click (object sender, EventArgs e) {if (useraddevent! = null) Useraddevent (this     

Take the Userage attribute below to explain the magic of UI interface. When the backend code to get the age value on the interface, just need get property, to update the interface display, just need set property. At this time, the back-end code for the interface operation, is abstracted to the userage properties of the operation, that is, and the specific interface display is irrelevant.

4.3 The bridge between Presenter--model and view

In the back-end code mentioned above, p and M are included. M, like MVC, refers to logical code. P is the bridge between the model and view, which is responsible for combining the corresponding model with the view.

For the above Iuseradd, the corresponding presenter code is:

PublicClassUseraddpresenter:ipresenter {PrivateReadOnlyIuser _model;PrivateReadOnlyIuseradd _view;PrivateReadOnly Applicationfacade _facade = applicationfacade.instance;//The facade here is for communication between presenter, and the full code can be seen in detail.//In the presenter constructor, the view and model are passed in as argumentsPublicUseraddpresenter (Iuser model, Iuseradd view) {_model =Model _view =View Wireupviewevents (); }Privatevoid Wireupviewevents () {_view. Useraddevent += _view_useradd;} //// send user_added messages to the system (the other UI parts of the system receive messages, such as the DataGrid here , it refreshes after receiving user_added) private void _view_useradd ( Span style= "color: #0000ff;" >object sender, EventArgs e) {var user = new _view. UserName, age = Convert.ToInt32 (_view. Userage)}; _model. AddItem (user); _facade. SendNotification (applicationfacade.user_added); }} 

4.4 MVP's code structure and timing diagram

The code structure and timing diagram of the MVP here will help to understand the MVP pattern better.

4.5 MVP Model Summary

In the MVP, presenter completely separates the model from the view, and the main program logic is implemented in presenter. Furthermore, presenter is not directly related to the specific view, but interacts through a well-defined interface, allowing the presenter to be kept constant when the view is changed, that is, reuse! Not only that, we can also write Test view, simulate the user's various operations, so as to achieve the test of presenter-without the need to use automated testing tools. We can even test the logic of presenter by writing a mock Object (that is, an interface that implements the model and view, but no concrete content) when the model and view are not finished.

The MVP Advantage

1, the model and the view completely separate, we can modify the view without affecting the model 2, can more efficient use of the model, because all the interaction occurs in a place--presenter internal 3, we can use a presener for multiple views, without the need to change presenter logic.     This feature is very useful because view changes are always more frequent than models. 4. If we put logic in presenter, then we can test the logic out of the user interface (unit test)

Five, MVVM mode

Design idea of 5.1 MVVM pattern

In the MVVM pattern, a viewmodel and a view match, which does not have the IView interface in the MVP, but the full and view bindings, all changes in the view are automatically updated to ViewModel. Any changes to the ViewModel are also automatically synchronized to the view display.

The reason this automatic synchronization is possible is that the properties in ViewModel implement an interface such as observable, which means that when a property's set method is used, the property modification event is triggered at the same time, so that the bound UI is automatically refreshed. (in WPF, this observable interface is inotifypropertychanged; in Knockoutjs, it is implemented by the function ko.observable () and ko.observrablecollection ())

So MVVM is a step ahead of the MVP, in the MVP, V is the interface iview, which solves the interface UI coupling; While MVVM simply integrates seamlessly with ViewModel and UI, ViewModel directly represents the UI. But MVVM does this by relying on specific platforms and technologies, such as WPF and Knockoutjs, which is why ViewModel does not need to implement interfaces because, in essence, the use of the MVVM pattern for specific platforms and technologies is a platform that cannot replace the UI. .

5.2 MVVM Pattern Structure diagram

Here is the structure diagram of the MVVM pattern, which helps to understand the MVVM pattern more easily:

Six, MVC, MVP and MVVM pattern Usage Scenarios Summary

Because it is not possible to support bidirectional binding of data and interfaces as well as monitoring of events in WinForm like WPF, MVP is the best choice in WinForm. Using knockout in WPF and HTML interfaces, observable is implemented, so use MVVM. (It should be said that WPF is designed for use with MVVM) in Web applications, because HTTP works in a request-and-response manner and cannot remain connected. So MVC is the best choice when it's impossible to get the message passing between presenter in the MVP and the ViewModel and interface in MVVM.

Transferred from: http://www.cnblogs.com/JustRun1983/p/3679827.html

MVC, MVP, MVVM comparisons and differences

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.