54
I O C O O D SG A INTRODUCTIONTO DESIGNPATTERN MVVM Jaffal Hasan November 2009

MVVM Design Pattern - Model View ViewModel

Embed Size (px)

DESCRIPTION

Introduction to Design patterns, MVVM Design Pattern - Model View ViewModel, and a comparaison with MVC and MVP and normal multi layered and multi architecture application design pattern.

Citation preview

Page 1: MVVM Design Pattern - Model View ViewModel

I O C O O D S G AINTRODUCTION TO DESIGN PATTERNMVVM

Jaffal HasanNovember 2009

Page 2: MVVM Design Pattern - Model View ViewModel

AGENDA

Design Patterns OverviewDo ArabiaGIS needs a pattern?P tt lPatterns examplesOverview of MVC-MVP and MVVM design patternsH T h th i t tt ?How To choose the appropriate pattern?MVC, MVP or MVVM with WPF ?MVVMMVVM

View ConceptViewModel ConceptModel ConceptHow it works?

N S !Next Step !

Page 3: MVVM Design Pattern - Model View ViewModel

AGENDA

Design Patterns OverviewDo ArabiaGIS needs a pattern?P tt lPatterns examplesOverview of MVC-MVP and MVVM design patternsH T h th i t tt ?How To choose the appropriate pattern?MVC, MVP or MVVM with WPF ?MVVMMVVM

View ConceptViewModel ConceptModel ConceptHow it works?

N S !Next Step !

Page 4: MVVM Design Pattern - Model View ViewModel

DESIGN PATTERN OVERVIEW

Set of guidelinesProvide solutions to common software design

blproblemsConsists of one or several software design elements such as elements such as modules, interfaces, classes, objects, methods, functions, processes, threads, etc.,

Relationships among the elements, and a behavioral descriptionExample design patterns: Model/View/Controller

Page 5: MVVM Design Pattern - Model View ViewModel

DESIGN PATTERN OVERVIEW

Advantages:Improve the structure of softwareSi lif i tSimplify maintenanceShared language for communicatingSeparation of concernsSeparation of concernsMinimize logic needed in viewsEnhance testabilityReduce development timeEasy to customize applications

Disadvantages:Design pattern can be overkill in Simple UI

Page 6: MVVM Design Pattern - Model View ViewModel

AGENDA

Design Patterns OverviewDo ArabiaGIS needs a pattern?P tt lPatterns examplesOverview of MVC-MVP and MVVM design patternsH T h th i t tt ?How To choose the appropriate pattern?MVC, MVP or MVVM with WPF ?MVVMMVVM

View ConceptViewModel ConceptModel ConceptHow it works?

N S !Next Step !

Page 7: MVVM Design Pattern - Model View ViewModel

DO WE NEED A PATTERN?

Al Theyab

• ASP.NET• VB.NET• Web services

Political Party

• Silverlight• Web servicesParty• C#

LD• ASP.NET• VB.NET

PowerMap• VB 6

A• Access

Page 8: MVVM Design Pattern - Model View ViewModel

DO WE NEED A PATTERN?M lti l j tMultiple projects

Big size projects – Long time projectsEveryone speaks a different languageEveryone speaks a different languageNo code maintainabilityResourcesResources

Human resources: Developers – analysts – QATechnical resources: ServersResource moving from project to projectResource SharingResource troubleshooting an applicationResource troubleshooting an application

Time loss in understanding The structureTh h lThe technology

Page 9: MVVM Design Pattern - Model View ViewModel

DO WE NEED A PATTERN?

Why don’t use the same concepts, guidelines and rules?

Page 10: MVVM Design Pattern - Model View ViewModel

UI, BUSINESS LOGIC AND DATA

Business applications consist of user interface (UI), business logic, and data models.

When UI, business logic and data are collapsed into one object in rich users interface it collapsed into one object in rich users interface, it can lead to some of the following problems:

Difficult to use the data outside that objectDifficult to use the data outside that objectHard to change the UI, when UI and data are locked in the same object.Hard to use multiple views of the same data.Difficult to synchronize multiple view of the same datadata.

Page 11: MVVM Design Pattern - Model View ViewModel

AGENDA

Design Patterns OverviewDo ArabiaGIS needs a pattern?P tt lPatterns examplesOverview of MVC-MVP and MVVM design patternsH T h th i t tt ?How To choose the appropriate pattern?MVC, MVP or MVVM with WPF ?MVVMMVVM

View ConceptViewModel ConceptModel ConceptHow it works?

N S !Next Step !

Page 12: MVVM Design Pattern - Model View ViewModel

DESIGN PATTERN CLASSIFICATIONS

Creational patternsStructural patternsBehavioral patterns

Page 13: MVVM Design Pattern - Model View ViewModel

DESIGN PATTERNS EXAMPLES

MVCModel – View – Controller

MVPMVPModel – View – PresenterIntroduced by Martin Fowler in 2004Introduced by Martin Fowler in 2004

MVVMModel View ViewModelModel – View – ViewModelOriginated from Microsoft as a specialization of the MVP

MVC# and ASP.NET MVCFor web application ( ASP.NET / VB.NET-C#.NET)

Page 14: MVVM Design Pattern - Model View ViewModel

AGENDA

Design Patterns OverviewDo ArabiaGIS needs a pattern?P tt lPatterns examplesOverview of MVC-MVP and MVVM design patternsH T h th i t tt ?How To choose the appropriate pattern?MVC, MVP or MVVM with WPF ?MVVMMVVM

View ConceptViewModel ConceptModel ConceptHow it works?

N S !Next Step !

Page 15: MVVM Design Pattern - Model View ViewModel

GOALS• Separation of concerns

• Decoupling the layers and componentsR d i d l i ( l i i )• Reducing development time ( multi processes at time)

• TestabilityFl ibilit• Flexibility• Minimal Code in UI• Changes in layers: DBMS • Changes in layers: DBMS • Change or use multiple platform to present data (mobile – web

..)

Page 16: MVVM Design Pattern - Model View ViewModel

MVC : MODEL – VIEW - CONTROLLER

llllControllerController

callscalls

ManipulatesManipulates

ViewViewManipulatesManipulates

ModelModel

Fires EventsFires Events

Page 17: MVVM Design Pattern - Model View ViewModel

MVC REFERENCES MAP

View

ModelController

MVC

Page 18: MVVM Design Pattern - Model View ViewModel

MVC :MODEL – VIEW - CONTROLLER

• Elementso Model: represents data and business rules/state

Vi d th d t t t i ibl lo View: renders the data or state; visible layero Controller: manages Views & user interaction;

coordinates with one or more Models• Guidelines

o Controller doesn’t know anything about the Viewy go Views can switch Controllerso Single Controller usable by multiple Viewso View subscribes to Model change events

Page 19: MVVM Design Pattern - Model View ViewModel

3 TIERS AND 3 LAYERSN tier architecture is about splitting up an application in different (logical and or physical ) layers UI on a machine (or set of machines) layers, UI on a machine (or set of machines), Business logic and services on another...Layered architecture Development model where Layered architecture Development model where presentation, business logic and data are separated.

Page 20: MVVM Design Pattern - Model View ViewModel

MVC VS. 3-LAYERS

33-Layers architecture MVC architecture

ModelPL

G t th i t i

BLVie Controller

Gets the appropriate view

View Controller

• The controller controls and Model

DALpresents – BL presents the data• Linear vs. triangular• Can be implemented together

MVC h id li PL id li • MVC has guidelines – PL no guidelines

Page 21: MVVM Design Pattern - Model View ViewModel

MVCMVC comes in different flavors

MVC active modelthe model must notify the views to refresh the displaythe model must notify the views to refresh the display

MVC passive modelThe controller modifies the model and then informs the view that the model has changed and should be refreshed

Page 22: MVVM Design Pattern - Model View ViewModel

MODEL – VIEW - PRESENTER

PresenterPresenter

callscalls

ViewViewUpdatesUpdates

ModelModel

ManipulatesManipulates

Page 23: MVVM Design Pattern - Model View ViewModel

MODEL – VIEW - PRESENTER

ff f ? f • How does it differ from MVC? Presenter refers back to View but Controller does notElements• Elementso Model: represents data and business rules/stateo View: renders the data or state; visible layer

P Vi & i i di o Presenter: manages Views & user interaction; coordinates with one or more Models; can update the View directly

• Guidelineso Presenter refers to an abstraction (interface or abstract base-

class) of the View for testabilityP t d t M d l d th Vio Presenter updates Model and the View

o More testable than MVCo Less code behind than MVCo More separation of concepts than MVC

Page 24: MVVM Design Pattern - Model View ViewModel

MVP REFERENCES MAP

View

View

Presenter

ModelControllerModel

MVC MVP

Page 25: MVVM Design Pattern - Model View ViewModel

MODEL – VIEW - VIEWMODEL

llllViewView

ModelModel

callscalls

ViewViewManipulatesManipulates

Fires EventsFires Events

ModelModel

pp

Page 26: MVVM Design Pattern - Model View ViewModel

MODEL – VIEW - VIEWMODELHow does it differ from MVP? ViewModel does not need a reference to • How does it differ from MVP? ViewModel does not need a reference to a View

• Elementso Model: represents data and business rules/statepo View: renders the data or state; visible layero ViewModel: Coordinates with one or more Models; exposes properties for the

View to bind to• Guidelines• Guidelines

o View knows about the ViewModel but not the Modelo ViewModel knows about the Model but not the Viewo Model only knows about itselfyo View binds to properties in the ViewModelo ViewModel can combine state info and/or data from multiple Modelso .Net XAML classes expose a DataContext property to which the ViewModel

b b d ith d l ti l i d b hi dcan be bound either declaratively or in code behindo Changes to properties in ViewModel automatically propagate to the View –

no additional wiring needed!o Data changes made in the ViewModel, never the View

• More testable than MVC than either MVC or MVP

Page 27: MVVM Design Pattern - Model View ViewModel

MVVM REFERENCES MAP

ViewView

View

ViewModelPresenter

ModelControllerModelModel

MVC MVP MVVM

Page 28: MVVM Design Pattern - Model View ViewModel

BENEFITS

M d l itModularitydecoupling componentsallows each component to be versioned independently

k d b i di id l (UI DB worked on by individuals on team (UI person, DB person, etc)

Flexibilityl i l Vi f M d l ( b f d d k multiple Views for one Model (web frontend, desktop

frontend, mobile frontend, etc)replace one component (replace data storage from flat file to database)to database)

Maintainabilityonly change one component where bug exists, less risk in late changeslate changes

Testabilityeach component communicates through contract so each component can be unit tested independentlycomponent can be unit-tested independently

Page 29: MVVM Design Pattern - Model View ViewModel

AGENDA

Design Patterns OverviewDo ArabiaGIS needs a pattern?P tt lPatterns examplesOverview of MVC-MVP and MVVM design patternsH T h th i t tt ?How To choose the appropriate pattern?MVC, MVP or MVVM with WPF ?MVVMMVVM

View ConceptViewModel ConceptModel ConceptHow it works?

N S !Next Step !

Page 30: MVVM Design Pattern - Model View ViewModel

MVC, MVP OR MVVM ?

How to choose?Based on the usedt h l itechnologies.

Page 31: MVVM Design Pattern - Model View ViewModel

AGENDA

Design Patterns OverviewDo ArabiaGIS needs a pattern?P tt lPatterns examplesOverview of MVC-MVP and MVVM design patternsH T h th i t tt ?How To choose the appropriate pattern?MVC, MVP or MVVM with WPF ?MVVMMVVM

View ConceptViewModel ConceptModel ConceptHow it works?

N S !Next Step !

Page 32: MVVM Design Pattern - Model View ViewModel

W P F WPFWINDOWS PRESENTATION FOUNDATION WPFMVVM pattern adaptation

Page 33: MVVM Design Pattern - Model View ViewModel

WPF?

Page 34: MVVM Design Pattern - Model View ViewModel

WPFWPF d Sil li ht UI d l t l tf WPF and Silverlight are UI development platforms

Developer specialized in user interface design and human-computer interaction

Most powerful feature is the two way bindingMost people’s first attempts at WPF resemble their first forays into winforms or even a VB Centric approachforays into winforms, or even a VB Centric approach

Name all UI controlsImplement handlers for events coming from controls (i.e. Button “click etc) directly in code behindclick, etc) directly in code behindStore references to model objects in code behindWrite code directly populate named controls

Results:Coupled code-behind and XAML (View)View has become storage for data: no unit testingView has become storage for data: no unit testingNot making use of two way binding.

Page 35: MVVM Design Pattern - Model View ViewModel

MVC, MVP OR MVVM WITH WPF ?MVP can work with WPFBut

N t t ki f ll d t f t bi di f WPFNot taking full advantage of two way binding of WPFYou need to implement MVP style assessors for all your controls and write code to always callback to the view to set controls value.

Page 36: MVVM Design Pattern - Model View ViewModel

MICROSOFT CHOICE !Mi ft i MVVM i t ll t d l WPF Microsoft was using MVVM internally to develop WPF applications, such as Microsoft Expression Blend.

MVVM is targeted at modern UI development platforms MVVM is targeted at modern UI development platforms (WPF and Silverlight) [Wikipedia]MVVM was designed to make use of specific functions i WPF [Wiki di ]in WPF [Wikipedia]

WPFWPFWPFWPF

MVVMMVVMMVVMMVVM

SilverlightSilverlight

Page 37: MVVM Design Pattern - Model View ViewModel

AGENDA

Design Patterns OverviewDo ArabiaGIS needs a pattern?P tt lPatterns examplesOverview of MVC-MVP and MVVM design patternsH T h th i t tt ?How To choose the appropriate pattern?MVC, MVP or MVVM with WPF ?MVVMMVVM

View ConceptViewModel ConceptModel ConceptHow it works?

N S !Next Step !

Page 38: MVVM Design Pattern - Model View ViewModel

MVVM ORIGIN

MVC MVP MVVM

Originated from Microsoft as a specialization of the MVP design pattern introduced by Martin Fowlerg p ySpecific for the Windows Presentation Foundation (WPF). Largely based on the Model-view-controller pattern (MVC)

Page 39: MVVM Design Pattern - Model View ViewModel

MODEL – VIEW - VIEWMODEL

“ViewModel acts as a complete mirror of the view but it's a stand alone C# class – you can think of it as an adapter for the view” y p

Jason DolingerWPF Architect

Page 40: MVVM Design Pattern - Model View ViewModel

MODEL – VIEW - VIEWMODEL

View

•UserControl based

ViewModel

•Implements

Model

•No WPF related concepts•Xaml•Minimal code behind•Datacontext set to the

associated VM h dl

INotifyPropertyChanged•Expose Icommand•Handle validation•Adapter class between the

Vi d th M d l

•Event based mechanism to signal changes to the ViewModel

•May already exists before the introduction of WPF •No event handlers

•Data binding to VM (datas & commands)

View and the Model•Listen to Model’s events•Testable

the introduction of WPF mechanisms

Page 41: MVVM Design Pattern - Model View ViewModel

VIEW

UserControl basedXamlMinimal code behindNo event handlersDatacontext set to the associated VMData binding to VM (datas & commands)

Page 42: MVVM Design Pattern - Model View ViewModel

VIEW– USER CONTROL

A control created by a developer, usually by combining other controls, often intended for use in a specific applicationin a specific application

Page 43: MVVM Design Pattern - Model View ViewModel

VIEW– DATA CONTEXT

Th tit i t t th The entity is set to the DataContext for a control. The DataContext refers to a The DataContext refers to a source of data that can be bound to a target. The DataContext often is set to an instance of an entity.

Page 44: MVVM Design Pattern - Model View ViewModel

VIEW– DATA BINDING

Simple way to display and interact with dataA connection between the UI and a data object All d t t fl b t th tAllows data to flow between the twoAutomatedD t bi g h th h g t f Vi M d lDatabing push the changes to from ViewModelto View and From View To ViewModelPath: Bind a Dependency property to a binding sourcePath: Bind a Dependency property to a binding sourceMode:

One WayTwo WayOne Time

Page 45: MVVM Design Pattern - Model View ViewModel

VIEW– DATA BINDING

Binding Binding Binding Dependency Dependency Object Binding

SourceBinding SourcePropertyProperty

ModeMode

Page 46: MVVM Design Pattern - Model View ViewModel

VIEWMODEL

Implements INotifyPropertyChangedExpose IcommandHandle validationAdapter class between the View and the ModelListen to Model’s eventsTestable

Page 47: MVVM Design Pattern - Model View ViewModel

VIEWMODEL–INOTIFYPROPERTYCHANGED

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changedproperty value has changed.INotifyCollectionChanged for collections (Observable collections ): will fire (Observable collections ): will fire NotifyCollectionChanged event when items added/removed

Page 48: MVVM Design Pattern - Model View ViewModel

VIEWMODEL– ICOMMAND

Allow Multiple source to invoke it

Page 49: MVVM Design Pattern - Model View ViewModel

“you are on the right track when you almost NEVER have t t l ith N ”to name a control with x:Name”

Jason DolingerWPF ArchitectWPF Architect

Page 50: MVVM Design Pattern - Model View ViewModel

MODEL

No WPF related conceptsEvent based mechanism to signal changes to the Vi M d lViewModelMay already exists before the introduction of WPF mechanismsWPF mechanisms

Page 51: MVVM Design Pattern - Model View ViewModel

THE FULL IMAGE

Page 52: MVVM Design Pattern - Model View ViewModel

DEMO

Page 53: MVVM Design Pattern - Model View ViewModel

NEXT STEP?Web Applications appropriate design pattern?

MVC SharpASP NET MVCASP.NET MVC

Page 54: MVVM Design Pattern - Model View ViewModel

THANKS FOR LISTENINGTHANKS FOR LISTENING.Jaffal Hasanhjaffal@arabiagis [email protected]