【MVVM的定義】 程序員
MVVM的目的是什麼? web
簡單總結起來一句話:分離UI邏輯和業務邏輯。這一點和被你們熟知的MVP和MVC是一致的。 express
下面詳細來講明下這個問題,下面一段英文來自Msdn: 設計模式
The Model-View-ViewModel (MVVM) pattern helps you to cleanly separate the business and presentation logic of your application from its user interface (UI). Maintaining a clean separation between application logic and UI helps to address numerous development and design issues and can make your application much easier to test, maintain, and evolve. It can also greatly improve code re-use opportunities and allows developers and UI designers to more easily collaborate when developing their respective parts of the application. 架構
Using the MVVM pattern, the UI of the application and the underlying presentation and business logic is separated into three separate classes: the view, which encapsulates the UI and UI logic; the view model, which encapsulates presentation logic and state; and the model, which encapsulates the application's business logic and data. app
Prism includes samples and reference implementations that show how to implement the MVVM pattern in a Silverlight or Windows Presentation Foundation (WPF) application. The Prism Library also provides features that can help you implement the pattern in your own applications. These features embody the most common practices for implementing the MVVM pattern and are designed to support testability and to work well with Expression Blend and Visual Studio. dom
總結起來MVVM的好處有: async
一、分離業務邏輯(buiness logic)和表現層邏輯(presentation logic) mvvm
二、Support testability 易於測試,正如martin flower 在xunit partten中提到的,對於程序unit test的建設要在設計之初便有所考慮。(對於這點是容易被不少人忽略的,由於多數coder甚至都不清楚什麼叫Unit Test)而這一點事實上也是MVVM帶來的很重要的好處。 ide
三、從筆者的經從來看,mvvm的另外一個意義在於,提升團隊協做的效率。
爲何這麼說呢?類比《設計模式》一書,設計模式這本書的重要做用在於,給程序員之間一個很好的名字契約,所以溝通時,只須要說我用了XX模式,那麼對方很直觀便明白了具體的實現。一個標準的架構的意義也在於此,好比團隊使用MVVM來架構,那麼只須要團隊中的成員對MVVM有所瞭解,對各層的職責明確清楚,那麼接下來繼續要開展的工做就容易不少。這和招聘iOS研發要須要理解MVC是一個道理,你們都瞭解的統一的程序架構,是協做的很重要的前提。
看過了MVVM 的做用,咱們接下來要作的即是明確各層的職責。單純的把類名起名叫ViewModel卻不作VM該作的事情,那仍是建議壓根就不要起名爲VM來混淆試聽了。(不能說拿來一個橙子告訴別人我這是橘子,而別人質疑的時候,辯解到這是改良的橘子)(雖然MVVM和MVX系列很類似,但他也是單獨命名出來的,而不是叫作變種的MVP)
(所以建議不要再同其餘人交流的過程當中說,我用了MVVM架構,但說出來卻徹底不是那麼回事兒,乾脆說叫MVVMNB算了也省得產生誤會)
【MVVM各層的職責界定】
爲了權威仍然引用msdn中對於mvvm的各層的職責界定:
此圖很清晰的明確了各層的職責以及交互方式,結合說明咱們作進一步分析:
The View Class
The view's responsibility is to define the structure and appearance of what the user sees on the screen. Ideally, the code-behind of a view contains only a constructor that calls the InitializeComponent method. In some cases, the code-behind may contain UI logic code that implements visual behavior that is difficult or inefficient to express in Extensible Application Markup Language (XAML), such as complex animations, or when the code needs to directly manipulate visual elements that are part of the view. You should not put any logic code in the view that you need to unit test. Typically, logic code in the view's code-behind will be tested via a UI automation testing approach.
In Silverlight and WPF, data binding expressions in the view are evaluated against its data context. In MVVM, the view's data context is set to the view model. The view model implements properties and commands to which the view can bind and notifies the view of any changes in state through change notification events. There is typically a one-to-one relationship between a view and its view model.
To summarize, the view has the following key characteristics:
很清楚的能夠看出View的職責:
定義用戶在屏幕中所看到的各個UI元素。
須要說明的是:
一、通常狀況下在view的code behind裏面應只包含構造函數,構造函數中執行InitilizeComponent方法。例外的場景是,在xaml中不容易實現的複雜的ui邏輯等。
二、不該將任何須要進行單元測試的邏輯放到view層中
三、在MVVM中View的DataContext是在ViewModel中。一般狀況下View和ViewModel是一對一的關係
對於View層的理解比較簡單
The View Model Class
The view model in the MVVM pattern encapsulates the presentation logic and data for the view. It has no direct reference to the view or any knowledge about the view's specific implementation or type. The view model implements properties and commands to which the view can data bind and notifies the view of any state changes through change notification events. The properties and commands that the view model provides define the functionality to be offered by the UI, but the view determines how that functionality is to be rendered.
The view model is responsible for coordinating the view's interaction with any model classes that are required. Typically, there is a one-to many-relationship between the view model and the model classes. The view model may choose to expose model classes directly to the view so that controls in the view can data bind directly to them. In this case, the model classes will need to be designed to support data binding and the relevant change notification events. For more information about this scenario, see the section, Data Binding, later in this topic.
The view model may convert or manipulate model data so that it can be easily consumed by the view. The view model may define additional properties to specifically support the view; these properties would not normally be part of (or cannot be added to) the model. For example, the view model may combine the value of two fields to make it easier for the view to present, or it may calculate the number of characters remaining for input for fields with a maximum length. The view model may also implement data validation logic to ensure data consistency.
The view model may also define logical states the view can use to provide visual changes in the UI. The view may define layout or styling changes that reflect the state of the view model. For example, the view model may define a state that indicates that data is being submitted asynchronously to a web service. The view can display an animation during this state to provide visual feedback to the user.
Typically, the view model will define commands or actions that can be represented in the UI and that the user can invoke. A common example is when the view model provides a Submit command that allows the user submit data to a web service or to a data repository. The view may choose to represent that command with a button so that the user can click the button to submit the data. Typically, when the command becomes unavailable, its associated UI representation becomes disabled. Commands provide a way to encapsulate user actions and to cleanly separate them from their visual representation in the UI.
To summarize, the view model has the following key characteristics:
須要注意的:
一、對於VM的職責,有一點很是容易理解錯誤,就是VM和Business logic的關係。
View Model 從名字來看就能夠看出它是View的Model,所以它須要爲View提供數據,以及操做接口,View Model中不該該包含Business Logic
二、VIewModel與View的關係如上面的圖中所描述,ViewModel是不應知道View的,即ViewModel不應持有View的實例(It has no direct reference to the view or any knowledge about the view's specific implementation or type.)
三、ViewModel是能夠脫離View和Model進行Unit Test的(the view model is testable independently of the view and the model.)
四、View經過Binding的方式將ViewModel中定義的數據以及行爲(command)關聯到一塊兒
The Model Class
The model in the MVVM pattern encapsulates business logic and data. Business logic is defined as any application logic that is concerned with the retrieval and management of application data and for making sure that any business rules that ensure data consistency and validity are imposed. To maximize re-use opportunities, models should not contain any use case–specific or user task–specific behavior or application logic.
Typically, the model represents the client-side domain model for the application. It can define data structures based on the application's data model and any supporting business and validation logic. The model may also include the code to support data access and caching, though typically a separate data repository or service is employed for this. Often, the model and data access layer are generated as part of a data access or service strategy, such as the ADO.NET Entity Framework, WCF Data Services, or WCF RIA Services.
Typically, the model implements the facilities that make it easy to bind to the view. This usually means it supports property and collection changed notification through the INotifyPropertyChanged and INotifyCollectionChanged interfaces. Models classes that represent collections of objects typically derive from the ObservableCollection<T> class, which provides an implementation of the INotifyCollectionChanged interface.
The model may also support data validation and error reporting through the IDataErrorInfo (or INotifyDataErrorInfo) interfaces. These interfaces allow WPF and Silverlight data binding to be notified when values change so that the UI can be updated. They also enable support for data validation and error reporting in the UI layer.
The model has the following key characteristics:
須要說明的有:
一、Model層定義Business logic 和Data。
二、Model層不依賴於View和ViewModel層
總結
對於MVVM的職責劃分正如上面所闡述的,很清晰,如此劃分,咱們能夠很好的根據職責來組織代碼的結構,增長程序的可維護性
綜上,筆者的結論是,MVVM是配合WPF系列技術中Binding等強大特性而出現的一種程序的架構方式,清晰而簡單,值得推薦使用。
參考:
http://en.wikipedia.org/wiki/MVVM
http://msdn.microsoft.com/en-us/library/gg405484(v=pandp.40).aspx
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
http://stackoverflow.com/questions/1644453/why-mvvm-and-what-are-its-core-benefits
更多關於MVVM的討論歡迎加入qq羣:182659848