Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Design Patterns in ZK: Java MVVM as Model-View-Binder


Published on

Presentation made at the UK ZK Users Group

Published in: Technology, Education
  • Visioss® is the leading actor of security surveillance cameras and video surveillance system.

    Based on powerful independent research ability and persistent technical innovation, with the excellent technicians and managers, Visioss® is especially absorbed in studying, producing, and selling of surveillance products.

    Visioss® will persist in innovation during the development of high-technology, constantly exploring, facing the keen market competition environment and winning the preemptive opportunities of market.

    Visioss® Strategy and Goals:
    • Remember that Quality and Service are remembered long after the price is forgotten.
    • Establish a worldwide distribution system by providing outstanding dealer support with quality built innovative products at a competitive price.
    • Learn from our experience and benefit from our clients experience and knowledge.
    • Respond to our clients concerns in a timely fashion with reasonable solutions.
    • Engineer our products to provide useful benefits and solutions for the end user.
    • Remember our future success is assured by our continuing ability to meet our clients many needs. We recognize, that like us, they have to adapt quickly to rapidly changing technology in a highly competitive global marketing environment.
    • Learn from the past, live in the now and plan for the future.
    Are you sure you want to  Yes  No
    Your message goes here
  • The ideas discussed in this presentation are now in a published article 'Implementing event-driven GUI patterns using the ZK Java AJAX framework'
    Are you sure you want to  Yes  No
    Your message goes here
  • I am still fairly happy with this terminology of used in this deck but these days I would change the labels to match Martin Fowler's:

    * Slide 23 I would label 'Passive View'.
    * Slide 25 I would label 'Supervising Controller'.
    * Slide 30 I would label 'Presentation Model'.

    Using the standard alphabet soup notation:

    * Slide 23 is MVP (passive view extreme)
    * Slide 23 is MVVMP (a binding model pushed to by a presenter)
    * Slide 30 is MVVM (mediator extreme)
    Are you sure you want to  Yes  No
    Your message goes here
  • The latest source code with ZK6 'ZK Bind' for MVVM is discussed at
    Are you sure you want to  Yes  No
    Your message goes here
  • This deck pre-dates the official ZK Bind MVVM. Whilst everything it says about MVVM is applicable yet you should see the latest source code examples on github for the new bindings approach google: github simbo1905 zktodo2
    Are you sure you want to  Yes  No
    Your message goes here

Design Patterns in ZK: Java MVVM as Model-View-Binder

  1. 1. Presentation Patterns In ZK Simon Massey (Revised Q2 2012)
  2. 2. IntroductionFirst version of this presentation was given to the 2010 UK ZK Users GroupThe "ZK ToDo 2" patterns sample code is in the zkforge project svn repository github.comSample code has the same screen implimented three times; as MVP, MVC and MVVM (MVB)Published articles document the MVP and MVC versions. Article coming soon about MVVM...See references at the end
  3. 3. OverviewWhy Patterns?Patterns recap of View and ModelModel, View, Who? The third partBest practices for each layer
  4. 4. Why Patterns? Evolving SoftwareA business sponsor talks about the screens but requires a flexible business solutionScreens are likely to change all the way through to go-live and well beyondFeatures evolve slowly over time whilst the screens can change drasticallyCan you easily reskin / re-layout / rearrange your app to freshen your user experience?Making flexible and adaptable solutions is more rewarding than making brittle apps
  5. 5. Why Patterns? A Challenge!Reuse a "buy now" feature of your website in an iphone app (as XML over HTTP)This requires separation of View from Model
  6. 6. Programming In The View Business state stored in view<label id=”hiddenBookId” value=”${}” visible=”false”/><button label=”Buy Book”> View knows who and <attribute name=”onClick”><![CDATA[ how MyDao myDao = … ; // get daoand render mixed Update via jndi myDao.buyBook(, hiddenBookId.value); statusLabel.value = ”Thanks! Buy another book?”; ]]></attribute></button><label id=”statusLabel” value=””/>
  7. 7. Avoid Coding In The View"Separated Presentation” is a core patternPresentation is incidental to what the customer is logically doing which is the Use Case / User Story (e.g. "customer buys book")The presentation changes fast and often so separate it out from the business logicJunit testing of the presentation is trickyBusiness logic within the View stunts the flexibility of your software design
  8. 8. The Triumvirate ViewModel who?
  9. 9. Micro vs. MacroMuch of the literature about MVC describes the fine grained "micro-MVC" used to implement graphical components such as Swing/JSFWhen reading articles it helps to think "Is this micro-MVC or macro-MVC?"This century we tend to pick a winning UI component framework (ZK!) and focus on "macro-MVC" for complex business screensThis presentation talks about the macro world unless explicitly stated
  10. 10. The View ViewModel who?
  11. 11. View Best Practices"ZK Desktop == View" so mixing Java business logic into ZK code is mixing business logic into the ViewView components should not become business components: BuyNowButton extends Button // avoid!The View should observe the Model using the databinder (more on this later): org.zkoss.zkplus.databind.AnnotateDataBinder
  12. 12. View Has Micro ModelsA BindingModel is an "push through" to update the View. Writing to it updates the bound ViewThese micro models are not business domain models which organise application featuresListModelList is binding model class for Listbox listModelList = (ListModelList)listbox.getModel();AnnotateDataBinder uses such micro-models as part of its logic to sync data into the ViewIntbox and Datebox have "value" property as micro-Model as well as "visible" and "disabled"
  13. 13. ZK Micro-Model == ViewListbox Composer ListModelList (view layer) Collection<Book> books (business domain layer)
  14. 14. The Business Domain (Macro) Model View Model who?
  15. 15. Model Best PracticesThe Business Domain Model should have no compile time dependencies to the presentation frameworkEL and AnnotateDataBinder should load data from the Model into the View (avoid coding)Ideally the Model should be a rich Domain Model have both behaviour as well as stateBeware designs of proceedural code loading and saving DTOs as this is weak OOTry test driven development of encapsulated layers ("POJOs In Action" book)
  16. 16. The Other Bit... ViewModel who?
  17. 17. Alphabet SoupMVC: Model-View-Controller Often cited but do we really know it as well as we believe?MVP: Model-View-Presenter A specialism of MVC with a dominant controllerMVVM: Model-View-ViewModel The Microsoft WPF pattern of the Application Model but how do we use it with ZK?MVB: Model-View-Binder A clearer moniker for "MVVM" with ZK
  18. 18. MVC Has Many InterpretationsMartin Fowler: Different people reading about MVC in different places take different ideas from it and describe these as MVC.Anon on Stuff nearest the User becomes the View, stuff nearest the database becomes the Model, stuff in between becomes the Controller. Marketects then refer to their projects architecture as "MVC", borrowing that acronyms impressive lineage(!!!)
  19. 19. Controller Of What? View ? ?Model ? Controller
  20. 20. The Controller RevisitedTypically org.zkoss.zk.ui.util.Composer but what are its responsibilities?Does Controller read/write the Model? YesDoes Controller read/write the View? PerhapsDoes View read/write the Model? PossiblyIs separation of behaviour (Controller) from state (Model) the only game in town? NoIs databinding with AnnotateDataBinder part View, part Controller, or a separate thing?
  21. 21. Model-View-ZKComposerorg.zkoss.zk.ui.util.Composer usually used as the 3rd part of the patternWhether it is a Controller or a Presenter depends on the interactions with View and Model: Presenter – pushes to Passive View Controller – updates a model observed by the View ("Supervising Controller")Any mix or match of the above will be called MVC. People say "traditional MVC" to mean View observes the Model updated by Controller
  22. 22. Model-View-Presenter Legend compiles to View eventsModel Presenter
  23. 23. Model-View-PresenterThe View is the fully owned by the PresenterZkToDoControllerV1 implements ComposerPushes all updates into the Passive ViewZkToDoControllerV1 implements ListitemRenderPresenter reacts to View Event notifications and updates the ModelZkToDo2 app example zktodo2_a.zulFor code write-up google "Massey Small Talks/2008/ November/ZK "
  24. 24. Model-View-Controller Legend compiles to View bindings eventsModel Controller
  25. 25. Enter The BinderView observes the state of the Model using databinding<?init class=”org.zkoss.....AnnotateDataBinderInit”?>Uses EL annotations within the ZUL page <textbox value=”@{person.firstname}”/>The @{} annotations automatically reads/write your POJOs (no UI event handling code required as ZK Binder does the work automatically!)Google " mvc zk massey"
  26. 26. Controller Best PracticesAim to have the Controller and View not communicate with one another. Let the binder to the workHave the binder pull the data from the Model with load hints rather than having the composer push data into the view model <textbox value=”@{person.firstname, load-after=buyButton.onClick}”/>zktodo2_b.zul example should have used more load-after hints and less Java code (see weather-station-mvvm.zul)
  27. 27. Model-View-ViewModelViewModel (Microsoft) is similar to an ApplicationModel (Smalltalk)Binder syncs application state into the ViewBinder maps View Events onto application methods (ICommand types in .Net C#)Gather both state and behaviour into one application model (stronger OO design)Binder is part of the View world. The application model is its model: so called it a "ViewModel"
  28. 28. ViewModel NirvānaJosh Smith ("ViewModel classes are easy to unit test … Views and unit tests are just two different types of ViewModel consumers""ViewModel classes can assist in properly designing user interfaces that are easy to skin""It is easy to just rip one view out and drop in a new view to render a ViewModel"Its all about the Binder. The name Model-View- Binder (MVB) highlights the key part
  29. 29. Model-View-Binder (Simplified) Legend View compiles to updates Binder loads <<reflection>> Application Model (has internal layers)
  30. 30. Model-View-Binder View Binder <<reflection>> Legend ViewModel compiles to command DomainModel load
  31. 31. Model-View-ZKBindComponents are bound to ViewModel by the Binder: <listcell label="@load("/>UI Events are dispatched to ViewModel methods by the Binder: <button label="Save" onClick="@command(save)"/ >ViewModel has annotations to inform Binder of any properties changed under the covers @NotifyChange({"reminders","selectedReminder"}) public void save() { … }
  32. 32. MVB/MVVM Best PracticesView Model has no references to View Objects only @Command and @NotifyChange annotationsCreate ViewModel classes which are "naked screens" onto which you overlay a zul skinViewModel is the Mediator of the Binder to the Model; it orchestrates the servicesUse Dependency Injection of service interfaces into the View ModeViewModel uses application services to get detached entites which it exposes to the Binder
  33. 33. SummaryPresentation patterns are all about modelling the features of our application independently of the frequently changing screensMVC, MVP, MVVM all have in common a separated viewModelling of the Model will lead to internal layersLabels such as "ViewModel" or "DataModel" or "ApplicationModel" are suggestions as to what is trying to be organised where
  34. 34. Summary (Cont 1)"B" is for Binder which plays a big part in MVC and major part of MVVM patterns. There is no "B" required for MVPThe Microsoft Binder is powerful and a core part of their framework. They invented MVVM as the best practice to organise a screen Model to leverage their BinderMVB is a moniker that names the new power in modern Separated View patterns: long live the Binder!
  35. 35. Summary (Cont 2)ZK has a mature AnnotateDataBinder for rendering POJO data values and state (visible/disabled) into ZK AJAX RIA Desktop ComponentsThe binding information is embedded into the Page (View) as "XML annotations"Add ZKToDo2 CommandBinder to fire application methods on the ViewModelViewModel has no compile time dependencies on ZK framework; can heavily junit with mock servicesUsing MVVM / MVB pattern is simply about getting the most out of the framework Binder
  36. 36. Summary (Cont 3)ZkToDo patterns demo code implements the same screen in each of MVP (zktodo_a.zul), MVC (zktodo_b.zul) and MVVM (zktodo_e.zul)
  37. 37. ReferencesMVC article Desktop MVC Patterns ZK, Spring & JPAOriginal MVP article SmallTalks 2008 Best MVC PatternsBook on how to build a layered domain model with Spring POJOs In ActionZK MVC Screen for POJOs In Action book code Test Driving ZK FoodToGoBook on designing ”domain objects first” for supple code Evans Domain Driven DesignMartin Fowler GUI Patterns pages UI ArchitecturesJosh Smiths inspirational Microsoft .Net MVVM Article
  38. 38. CorrectionsMarch 2012: Slide 13 had totally miss attributed Fowler where I was using the term "Presentation Model" to mean something totally different. Edited to call my concept "BindingModel"March 212: Slide 21 had miss labelled Passive View as Supervising Controller