Merge branch 'master' into bytecode-explanation

This commit is contained in:
Subhrodip Mohanta 2021-03-22 12:05:27 +05:30 committed by GitHub
commit b978c83993
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 924 additions and 259 deletions

View File

@ -9,21 +9,156 @@ tags:
---
## Intent
The Business Delegate pattern adds an abstraction layer between
presentation and business tiers. By using the pattern we gain loose coupling
between the tiers and encapsulate knowledge about how to locate, connect to,
and interact with the business objects that make up the application.
## Explanation
Real world example
> A mobile phone application promises to stream any movie in existence to your phone. It captures
> the user's search string and passes this on to the business delegate. The business delegate
> selects the most suitable video streaming service and plays the video from there.
In Plain Words
> Business delegate adds an abstraction layer between the presentation and business tiers.
Wikipedia says
> Business delegate is a Java EE design pattern. This pattern is directing to reduce the coupling
> in between business services and the connected presentation tier, and to hide the implementation
> details of services (including lookup and accessibility of EJB architecture). Business delegates
> acts as an adaptor to invoke business objects from the presentation tier.
**Programmatic Example**
First, we have an abstraction for video streaming services and a couple of implementations.
```java
public interface VideoStreamingService {
void doProcessing();
}
@Slf4j
public class NetflixService implements VideoStreamingService {
@Override
public void doProcessing() {
LOGGER.info("NetflixService is now processing");
}
}
@Slf4j
public class YouTubeService implements VideoStreamingService {
@Override
public void doProcessing() {
LOGGER.info("YouTubeService is now processing");
}
}
```
Then we have a lookup service that decides which video streaming service is used.
```java
@Setter
public class BusinessLookup {
private NetflixService netflixService;
private YouTubeService youTubeService;
public VideoStreamingService getBusinessService(String movie) {
if (movie.toLowerCase(Locale.ROOT).contains("die hard")) {
return netflixService;
} else {
return youTubeService;
}
}
}
```
The business delegate uses a business lookup to route movie playback requests to a suitable
video streaming service.
```java
@Setter
public class BusinessDelegate {
private BusinessLookup lookupService;
public void playbackMovie(String movie) {
VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie);
videoStreamingService.doProcessing();
}
}
```
The mobile client utilizes business delegate to call the business tier.
```java
public class MobileClient {
private final BusinessDelegate businessDelegate;
public MobileClient(BusinessDelegate businessDelegate) {
this.businessDelegate = businessDelegate;
}
public void playbackMovie(String movie) {
businessDelegate.playbackMovie(movie);
}
}
```
Finally, we can show the full example in action.
```java
public static void main(String[] args) {
// prepare the objects
var businessDelegate = new BusinessDelegate();
var businessLookup = new BusinessLookup();
businessLookup.setNetflixService(new NetflixService());
businessLookup.setYouTubeService(new YouTubeService());
businessDelegate.setLookupService(businessLookup);
// create the client and use the business delegate
var client = new MobileClient(businessDelegate);
client.playbackMovie("Die Hard 2");
client.playbackMovie("Maradona: The Greatest Ever");
}
```
Here is the console output.
```
21:15:33.790 [main] INFO com.iluwatar.business.delegate.NetflixService - NetflixService is now processing
21:15:33.794 [main] INFO com.iluwatar.business.delegate.YouTubeService - YouTubeService is now processing
```
## Class diagram
![alt text](./etc/business-delegate.png "Business Delegate")
![alt text](./etc/business-delegate.urm.png "Business Delegate")
## Related patterns
* [Service locator pattern](https://java-design-patterns.com/patterns/service-locator/)
## Applicability
Use the Business Delegate pattern when
* you want loose coupling between presentation and business tiers
* you want to orchestrate calls to multiple business services
* you want to encapsulate service lookups and service calls
* You want loose coupling between presentation and business tiers
* You want to orchestrate calls to multiple business services
* You want to encapsulate service lookups and service calls
## Tutorials
* [Business Delegate Pattern at TutorialsPoint](https://www.tutorialspoint.com/design_pattern/business_delegate_pattern.htm)
## Credits
* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31)
* [Core J2EE Patterns: Best Practices and Design Strategies](https://www.amazon.com/gp/product/0130648841/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0130648841&linkId=a0100de2b28c71ede8db1757fb2b5947)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

View File

@ -1,136 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
realizations="true" associations="true" dependencies="false" nesting-relationships="true">
<class id="1" language="java" name="com.iluwatar.business.delegate.BusinessDelegate" project="business-delegate"
file="/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="272" y="219"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="2" language="java" name="com.iluwatar.business.delegate.Client" project="business-delegate"
file="/business-delegate/src/main/java/com/iluwatar/business/delegate/Client.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="272" y="64"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<enumeration id="3" language="java" name="com.iluwatar.business.delegate.ServiceType" project="business-delegate"
file="/business-delegate/src/main/java/com/iluwatar/business/delegate/ServiceType.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="89" y="383"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</enumeration>
<interface id="4" language="java" name="com.iluwatar.business.delegate.BusinessService" project="business-delegate"
file="/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessService.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="630" y="365"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</interface>
<class id="5" language="java" name="com.iluwatar.business.delegate.JmsService" project="business-delegate"
file="/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="489" y="210"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="6" language="java" name="com.iluwatar.business.delegate.BusinessLookup" project="business-delegate"
file="/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="360" y="399"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="7" language="java" name="com.iluwatar.business.delegate.EjbService" project="business-delegate"
file="/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="668" y="210"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<realization id="8">
<end type="SOURCE" refId="7"/>
<end type="TARGET" refId="4"/>
</realization>
<association id="9">
<end type="SOURCE" refId="1" navigable="false">
<attribute id="10" name="lookupService">
<position height="0" width="0" x="0" y="0"/>
</attribute>
<multiplicity id="11" minimum="0" maximum="1">
<position height="0" width="0" x="0" y="0"/>
</multiplicity>
</end>
<end type="TARGET" refId="6" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="12">
<end type="SOURCE" refId="1" navigable="false">
<attribute id="13" name="serviceType">
<position height="0" width="0" x="0" y="0"/>
</attribute>
<multiplicity id="14" minimum="0" maximum="1">
<position height="0" width="0" x="0" y="0"/>
</multiplicity>
</end>
<end type="TARGET" refId="3" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<realization id="15">
<end type="SOURCE" refId="5"/>
<end type="TARGET" refId="4"/>
</realization>
<association id="16">
<end type="SOURCE" refId="2" navigable="false">
<attribute id="17" name="businessDelegate">
<position height="0" width="0" x="0" y="0"/>
</attribute>
<multiplicity id="18" minimum="0" maximum="1">
<position height="0" width="0" x="0" y="0"/>
</multiplicity>
</end>
<end type="TARGET" refId="1" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="19">
<end type="SOURCE" refId="1" navigable="false">
<attribute id="20" name="businessService">
<position height="0" width="0" x="0" y="0"/>
</attribute>
<multiplicity id="21" minimum="0" maximum="1">
<position height="0" width="0" x="0" y="0"/>
</multiplicity>
</end>
<end type="TARGET" refId="4" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</classifier-display>
<association-display labels="true" multiplicity="true"/>
</class-diagram>

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

View File

@ -5,53 +5,42 @@ package com.iluwatar.business.delegate {
+ main(args : String[]) {static}
}
class BusinessDelegate {
- businessService : BusinessService
- lookupService : BusinessLookup
- serviceType : ServiceType
+ BusinessDelegate()
+ doTask()
+ setLookupService(businessLookup : BusinessLookup)
+ setServiceType(serviceType : ServiceType)
+ playbackMovie(movie : String)
+ setLookupService(lookupService : BusinessLookup)
}
class BusinessLookup {
- ejbService : EjbService
- jmsService : JmsService
- netflixService : NetflixService
- youTubeService : YouTubeService
+ BusinessLookup()
+ getBusinessService(serviceType : ServiceType) : BusinessService
+ setEjbService(ejbService : EjbService)
+ setJmsService(jmsService : JmsService)
+ getBusinessService(movie : String) : VideoStreamingService
+ setNetflixService(netflixService : NetflixService)
+ setYouTubeService(youTubeService : YouTubeService)
}
interface BusinessService {
class MobileClient {
- businessDelegate : BusinessDelegate
+ MobileClient(businessDelegate : BusinessDelegate)
+ playbackMovie(movie : String)
}
class NetflixService {
- LOGGER : Logger {static}
+ NetflixService()
+ doProcessing()
}
interface VideoStreamingService {
+ doProcessing() {abstract}
}
class Client {
- businessDelegate : BusinessDelegate
+ Client(businessDelegate : BusinessDelegate)
+ doTask()
}
class EjbService {
class YouTubeService {
- LOGGER : Logger {static}
+ EjbService()
+ YouTubeService()
+ doProcessing()
}
class JmsService {
- LOGGER : Logger {static}
+ JmsService()
+ doProcessing()
}
enum ServiceType {
+ EJB {static}
+ JMS {static}
+ valueOf(name : String) : ServiceType {static}
+ values() : ServiceType[] {static}
}
}
BusinessLookup --> "-ejbService" EjbService
BusinessDelegate --> "-serviceType" ServiceType
Client --> "-businessDelegate" BusinessDelegate
BusinessDelegate --> "-businessService" BusinessService
BusinessLookup --> "-netflixService" NetflixService
BusinessLookup --> "-youTubeService" YouTubeService
MobileClient --> "-businessDelegate" BusinessDelegate
BusinessDelegate --> "-lookupService" BusinessLookup
BusinessLookup --> "-jmsService" JmsService
EjbService ..|> BusinessService
JmsService ..|> BusinessService
NetflixService ..|> VideoStreamingService
YouTubeService ..|> VideoStreamingService
@enduml

View File

@ -33,9 +33,9 @@ package com.iluwatar.business.delegate;
* retrieved through service lookups. The Business Delegate itself may contain business logic too
* potentially tying together multiple service calls, exception handling, retrying etc.
*
* <p>In this example the client ({@link Client}) utilizes a business delegate (
* {@link BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate
* service and makes the service call.
* <p>In this example the client ({@link MobileClient}) utilizes a business delegate (
* {@link BusinessDelegate}) to search for movies in video streaming services. The Business Delegate
* then selects the appropriate service and makes the service call.
*/
public class App {
@ -46,18 +46,16 @@ public class App {
*/
public static void main(String[] args) {
// prepare the objects
var businessDelegate = new BusinessDelegate();
var businessLookup = new BusinessLookup();
businessLookup.setEjbService(new EjbService());
businessLookup.setJmsService(new JmsService());
businessLookup.setNetflixService(new NetflixService());
businessLookup.setYouTubeService(new YouTubeService());
businessDelegate.setLookupService(businessLookup);
businessDelegate.setServiceType(ServiceType.EJB);
var client = new Client(businessDelegate);
client.doTask();
businessDelegate.setServiceType(ServiceType.JMS);
client.doTask();
// create the client and use the business delegate
var client = new MobileClient(businessDelegate);
client.playbackMovie("Die Hard 2");
client.playbackMovie("Maradona: The Greatest Ever");
}
}

View File

@ -23,24 +23,18 @@
package com.iluwatar.business.delegate;
import lombok.Setter;
/**
* BusinessDelegate separates the presentation and business tiers.
*/
@Setter
public class BusinessDelegate {
private BusinessLookup lookupService;
private ServiceType serviceType;
public void setLookupService(BusinessLookup businessLookup) {
this.lookupService = businessLookup;
}
public void setServiceType(ServiceType serviceType) {
this.serviceType = serviceType;
}
public void doTask() {
BusinessService businessService = lookupService.getBusinessService(serviceType);
businessService.doProcessing();
public void playbackMovie(String movie) {
VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie);
videoStreamingService.doProcessing();
}
}

View File

@ -23,6 +23,7 @@
package com.iluwatar.business.delegate;
import java.util.Locale;
import lombok.Setter;
/**
@ -31,21 +32,21 @@ import lombok.Setter;
@Setter
public class BusinessLookup {
private EjbService ejbService;
private NetflixService netflixService;
private JmsService jmsService;
private YouTubeService youTubeService;
/**
* Gets service instance based on service type.
* Gets service instance based on given movie search string.
*
* @param serviceType Type of service instance to be returned.
* @param movie Search string for the movie.
* @return Service instance.
*/
public BusinessService getBusinessService(ServiceType serviceType) {
if (serviceType.equals(ServiceType.EJB)) {
return ejbService;
public VideoStreamingService getBusinessService(String movie) {
if (movie.toLowerCase(Locale.ROOT).contains("die hard")) {
return netflixService;
} else {
return jmsService;
return youTubeService;
}
}
}

View File

@ -24,17 +24,17 @@
package com.iluwatar.business.delegate;
/**
* Client utilizes BusinessDelegate to call the business tier.
* MobileClient utilizes BusinessDelegate to call the business tier.
*/
public class Client {
public class MobileClient {
private final BusinessDelegate businessDelegate;
public Client(BusinessDelegate businessDelegate) {
public MobileClient(BusinessDelegate businessDelegate) {
this.businessDelegate = businessDelegate;
}
public void doTask() {
businessDelegate.doTask();
public void playbackMovie(String movie) {
businessDelegate.playbackMovie(movie);
}
}

View File

@ -26,13 +26,13 @@ package com.iluwatar.business.delegate;
import lombok.extern.slf4j.Slf4j;
/**
* Service EJB implementation.
* NetflixService implementation.
*/
@Slf4j
public class EjbService implements BusinessService {
public class NetflixService implements VideoStreamingService {
@Override
public void doProcessing() {
LOGGER.info("EjbService is now processing");
LOGGER.info("NetflixService is now processing");
}
}

View File

@ -24,9 +24,9 @@
package com.iluwatar.business.delegate;
/**
* Interface for service implementations.
* Interface for video streaming service implementations.
*/
public interface BusinessService {
public interface VideoStreamingService {
void doProcessing();
}

View File

@ -26,13 +26,13 @@ package com.iluwatar.business.delegate;
import lombok.extern.slf4j.Slf4j;
/**
* Service JMS implementation.
* YouTubeService implementation.
*/
@Slf4j
public class JmsService implements BusinessService {
public class YouTubeService implements VideoStreamingService {
@Override
public void doProcessing() {
LOGGER.info("JmsService is now processing");
LOGGER.info("YouTubeService is now processing");
}
}

View File

@ -26,25 +26,20 @@ package com.iluwatar.business.delegate;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* The Business Delegate pattern adds an abstraction layer between the presentation and business
* tiers. By using the pattern we gain loose coupling between the tiers. The Business Delegate
* encapsulates knowledge about how to locate, connect to, and interact with the business objects
* that make up the application.
*
* <p>Some of the services the Business Delegate uses are instantiated directly, and some can be
* retrieved through service lookups. The Business Delegate itself may contain business logic too
* potentially tying together multiple service calls, exception handling, retrying etc.
* Tests for the {@link BusinessDelegate}
*/
class BusinessDelegateTest {
private EjbService ejbService;
private NetflixService netflixService;
private JmsService jmsService;
private YouTubeService youTubeService;
private BusinessDelegate businessDelegate;
@ -54,19 +49,19 @@ class BusinessDelegateTest {
*/
@BeforeEach
public void setup() {
ejbService = spy(new EjbService());
jmsService = spy(new JmsService());
netflixService = spy(new NetflixService());
youTubeService = spy(new YouTubeService());
BusinessLookup businessLookup = spy(new BusinessLookup());
businessLookup.setEjbService(ejbService);
businessLookup.setJmsService(jmsService);
businessLookup.setNetflixService(netflixService);
businessLookup.setYouTubeService(youTubeService);
businessDelegate = spy(new BusinessDelegate());
businessDelegate.setLookupService(businessLookup);
}
/**
* In this example the client ({@link Client}) utilizes a business delegate (
* In this example the client ({@link MobileClient}) utilizes a business delegate (
* {@link BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate
* service and makes the service call.
*/
@ -74,26 +69,20 @@ class BusinessDelegateTest {
void testBusinessDelegate() {
// setup a client object
var client = new Client(businessDelegate);
// set the service type
businessDelegate.setServiceType(ServiceType.EJB);
var client = new MobileClient(businessDelegate);
// action
client.doTask();
client.playbackMovie("Die hard");
// verifying that the businessDelegate was used by client during doTask() method.
verify(businessDelegate).doTask();
verify(ejbService).doProcessing();
// set the service type
businessDelegate.setServiceType(ServiceType.JMS);
// verifying that the businessDelegate was used by client during playbackMovie() method.
verify(businessDelegate).playbackMovie(anyString());
verify(netflixService).doProcessing();
// action
client.doTask();
client.playbackMovie("Maradona");
// verifying that the businessDelegate was used by client during doTask() method.
verify(businessDelegate, times(2)).doTask();
verify(jmsService).doProcessing();
verify(businessDelegate, times(2)).playbackMovie(anyString());
verify(youTubeService).doProcessing();
}
}

View File

@ -0,0 +1,145 @@
---
layout: pattern
title: Model-View-ViewModel
folder: model-view-viewmodel
permalink: /patterns/model-view-viewmodel/
categories: Architectural
tags:
- Decoupling
---
## Also known as
ModelViewBinder
## Intent
To apply "[Separation of Concerns](https://java-design-patterns.com/principles/#separation-of-concerns)" to separate the logic from the UI components and allow developers to work on UI without affecting the logic and vice versa.
## Explanation
Wikipedia says
> Modelviewviewmodel (MVVM) is a software architectural pattern that facilitates the separation of the development of the graphical user interface (the view) be it via a markup language or GUI code from the development of the business logic or back-end logic (the model) so that the view is not dependent on any specific model platform.
**Programmatic Example**
Zkoss implementation:
> ViewModel will hold the business logic and expose the data from model to View
```java
public class BookViewModel {
@WireVariable
private List<Book> bookList;
private Book selectedBook;
private BookService bookService = new BookServiceImpl();
public Book getSelectedBook() {
return selectedBook;
}
@NotifyChange("selectedBook")
public void setSelectedBook(Book selectedBook) {
this.selectedBook = selectedBook;
}
public List<Book> getBookList() {
return bookService.load();
}
/** Deleting a book.
*/
@Command
@NotifyChange({"selectedBook","bookList"})
public void deleteBook() {
if (selectedBook != null) {
getBookList().remove(selectedBook);
selectedBook = null;
}
}
```
> View will have no logic, only UI elements
```xml
<zk>
<window title="List of Books" border="normal" width="600px" apply="org.zkoss.bind.BindComposer" viewModel="@id('vm') @init('com.iluwatar.model.view.viewmodel.BookViewModel')">
<vbox hflex="true">
<listbox model="@bind(vm.bookList)" selectedItem="@bind(vm.selectedBook)" height="400px" mold="paging">
<listhead>
<listheader label="Book Name"/>
<listheader label="Author"/>
</listhead>
<template name="model" var="book">
<listitem >
<listcell label="@bind(book.name)"/>
<listcell label="@bind(book.author)"/>
</listitem>
</template>
</listbox>
</vbox>
<toolbar>
        <button label="Delete" onClick="@command('deleteBook')" disabled="@load(empty vm.selectedBook)" />
    </toolbar>
<hbox style="margin-top:20px" visible="@bind(not empty vm.selectedBook)">
<vbox>
<hlayout>
Book Name : <label value="@bind(vm.selectedBook.name)" style="font-weight:bold"/>
</hlayout>
<hlayout>
Book Author : <label value="@bind(vm.selectedBook.author)" style="font-weight:bold"/>
</hlayout>
<hlayout>
Book Description : <label value="@bind(vm.selectedBook.description)" style="font-weight:bold"/>
</hlayout>
</vbox>
</hbox>
</window>
</zk>
```
Note:
* To deploy this, go to model-view-viewmodel folder and run:
* mvn clean install
* mvn jetty:run -Djetty.http.port=9911
* In browser, http://localhost:9911/model-view-viewmodel/
## Class diagram
![alt text](./etc/model-view-viewmodel.png "MVVM pattern class diagram")
## Applicability
* When looking for clean architecture, with better reusability, testability and maintainability.
## Tutorials
* [Zkoss Demo](https://www.zkoss.org/zkdemo/getting_started/mvvm)
* [Learn MVVM](https://www.learnmvvm.com/)
* [Android Developer CodeLabs](https://codelabs.developers.google.com/codelabs/android-databinding)
## Typical Use Case
* Android apps
* .NET framework applications
* JavaScript applications
## Real world examples
* ZK Framework [zkoss.org](https://www.zkoss.org/)
* KnockoutJS [knockoutjs.com](https://knockoutjs.com/)
## Consequences
* John Gossman has criticized the MVVM pattern and its application in specific uses, stating that MVVM can be "overkill" when creating simple user interfaces. For larger applications, he believes that generalizing the viewmodel upfront can be difficult, and that large-scale data binding can lead to lower performance - Ref: [MVVM-Wiki](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel)
* Can be hard to design ViewModel for larger applications.
* For complex databinding, debugging can be difficult.
## Credits
* [ZK MVVM](https://www.zkoss.org/wiki/ZK%20Developer's%20Reference/MVVM)
* [GeeksforGeeks MVVM Intro](https://www.geeksforgeeks.org/introduction-to-model-view-view-model-mvvm/)
* [ZK MVVM Book](http://books.zkoss.org/zk-mvvm-book/9.5/)
* [Microsoft MVVM](https://docs.microsoft.com/en-us/archive/msdn-magazine/2009/february/patterns-wpf-apps-with-the-model-view-viewmodel-design-pattern)

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

View File

@ -0,0 +1,43 @@
@startuml
package com.iluwatar.model.view.viewmodel {
class Book {
- author : String
- description : String
- name : String
+ Book(name : String, author : String, description : String)
# canEqual(other : Object) : boolean
+ equals(o : Object) : boolean
+ getAuthor() : String
+ getDescription() : String
+ getName() : String
+ hashCode() : int
+ setAuthor(author : String)
+ setDescription(description : String)
+ setName(name : String)
+ toString() : String
}
interface BookService {
+ load() : List<Book> {abstract}
}
class BookServiceImpl {
- designPatternBooks : List<Book>
+ BookServiceImpl()
+ load() : List<Book>
}
class BookViewModel {
- bookList : List<Book>
- bookService : BookService
- selectedBook : Book
+ BookViewModel()
+ deleteBook()
+ getBookList() : List<Book>
+ getSelectedBook() : Book
+ setSelectedBook(selectedBook : Book)
}
}
BookViewModel --> "-bookService" BookService
BookServiceImpl --> "-designPatternBooks" Book
BookViewModel --> "-bookList" Book
BookViewModel --> "-selectedBook" Book
BookServiceImpl ..|> BookService
@enduml

View File

@ -0,0 +1,2 @@
config.stopBubbling = true
lombok.addLombokGeneratedAnnotation = true

View File

@ -0,0 +1,115 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.24.0-SNAPSHOT</version>
</parent>
<groupId>com.iluwatar</groupId>
<artifactId>model-view-viewmodel</artifactId>
<version>1.24.0-SNAPSHOT</version>
<properties>
<zk.version>9.0.0</zk.version>
<guava.version>19.0</guava.version>
<jetty-maven-plugin.version>9.4.28.v20200408</jetty-maven-plugin.version>
<maven-war-plugin.version>2.1.1</maven-war-plugin.version>
<maven-assembly-plugin.version>2.2</maven-assembly-plugin.version>
<maven.build.timestamp.format>yyyy-MM-dd</maven.build.timestamp.format>
<packname>-${project.version}-FL-${maven.build.timestamp}</packname>
</properties>
<packaging>war</packaging>
<name>model-view-viewmodel</name>
<description>model-view-viewmodel</description>
<licenses>
<license>
<name>GNU LESSER GENERAL PUBLIC LICENSE, Version 3</name>
<url>https://www.gnu.org/licenses/lgpl.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<repositories>
<repository>
<id>ZK CE</id>
<name>ZK CE Repository</name>
<url>https://mavensync.zkoss.org/maven2</url>
</repository>
<repository>
<id>ZK EVAL</id>
<name>ZK Evaluation Repository</name>
<url>https://mavensync.zkoss.org/eval</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>zkmaven</id>
<name>ZK Maven Plugin Repository</name>
<url>https://mavensync.zkoss.org/maven2/</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkbind</artifactId>
<version>${zk.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-testlib</artifactId>
<version>${guava.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- Run with Jetty -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty-maven-plugin.version}</version>
<configuration>
<webApp>
<contextPath>/${project.artifactId}</contextPath>
<allowDuplicateFragmentNames>true</allowDuplicateFragmentNames>
</webApp>
<scanIntervalSeconds>5</scanIntervalSeconds>
</configuration>
</plugin>
<!-- Build war -->
<plugin>
<artifactId>maven-war-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId>
<version>${maven-war-plugin.version}</version>
</plugin>
<!-- Pack zips -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>${maven-assembly-plugin.version}</version>
<executions>
<execution>
<id>webapp</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>model-view-viewmodel${packname}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/main/assembly/webapp.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,25 @@
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>webapp</id>
<formats>
<format>zip</format>
</formats>
<fileSets>
<fileSet>
<directory>${project.basedir}/src/main/java</directory>
<outputDirectory>/${project.artifactId}/src</outputDirectory>
</fileSet>
<fileSet>
<directory>${project.basedir}/src/main/webapp</directory>
<outputDirectory>/${project.artifactId}/WebContent</outputDirectory>
</fileSet>
</fileSets>
<files>
<file>
<source>${project.build.directory}/${project.artifactId}.war</source>
<outputDirectory>/</outputDirectory>
</file>
</files>
</assembly>

View File

@ -21,13 +21,17 @@
* THE SOFTWARE.
*/
package com.iluwatar.business.delegate;
package com.iluwatar.model.view.viewmodel;
/**
* Enumeration for service types.
*/
public enum ServiceType {
import lombok.AllArgsConstructor;
import lombok.Data;
@AllArgsConstructor
@Data
public class Book {
private String name;
private String author;
private String description;
EJB,
JMS
}

View File

@ -0,0 +1,10 @@
package com.iluwatar.model.view.viewmodel;
import java.util.List;
public interface BookService {
/* List all books
* @return all books
*/
public List<Book> load();
}

View File

@ -0,0 +1,38 @@
package com.iluwatar.model.view.viewmodel;
import java.util.ArrayList;
import java.util.List;
public class BookServiceImpl implements BookService {
private List<Book> designPatternBooks = new ArrayList<>();
/** Initializes Book Data.
* To be used and passed along in load method
* In this case, list design pattern books are initialized to be loaded.
*/
public BookServiceImpl() {
designPatternBooks.add(new Book(
"Head First Design Patterns: A Brain-Friendly Guide",
"Eric Freeman, Bert Bates, Kathy Sierra, Elisabeth Robson",
"Head First Design Patterns Description"));
designPatternBooks.add(new Book(
"Design Patterns: Elements of Reusable Object-Oriented Software",
"Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides",
"Design Patterns Description"));
designPatternBooks.add(new Book(
"Patterns of Enterprise Application Architecture", "Martin Fowler",
"Patterns of Enterprise Application Architecture Description"));
designPatternBooks.add(new Book(
"Design Patterns Explained", "Alan Shalloway, James Trott",
"Design Patterns Explained Description"));
designPatternBooks.add(new Book(
"Applying UML and Patterns: An Introduction to "
+ "Object-Oriented Analysis and Design and Iterative Development",
"Craig Larman", "Applying UML and Patterns Description"));
}
public List<Book> load() {
return designPatternBooks;
}
}

View File

@ -0,0 +1,43 @@
package com.iluwatar.model.view.viewmodel;
import java.util.List;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.select.annotation.WireVariable;
public class BookViewModel {
@WireVariable
private List<Book> bookList;
private Book selectedBook;
private BookService bookService = new BookServiceImpl();
public Book getSelectedBook() {
return selectedBook;
}
@NotifyChange("selectedBook")
public void setSelectedBook(Book selectedBook) {
this.selectedBook = selectedBook;
}
public List<Book> getBookList() {
return bookService.load();
}
/** Deleting a book.
* When event is triggered on click of Delete button,
* this method will be notified with the selected entry that will be referenced
* and used to delete the selected book from the list of books.
*/
@Command
@NotifyChange({"selectedBook","bookList"})
public void deleteBook() {
if (selectedBook != null) {
getBookList().remove(selectedBook);
selectedBook = null;
}
}
}

View File

@ -0,0 +1,8 @@
Manifest-Version: 1.0
Specification-Title: ZK Application
Specification-Version: 1.0
Specification-Vendor:
Implementation-Title:
Implementation-URL: http://your-website/
Implementation-Version: 1.0
Implementation-Vendor:

View File

@ -0,0 +1,114 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<description><![CDATA[My ZK Application]]></description>
<display-name>model-view-viewmodel</display-name>
<!-- ZK -->
<listener>
<description>ZK listener for session cleanup</description>
<listener-class>org.zkoss.zk.ui.http.HttpSessionListener</listener-class>
</listener>
<servlet>
<description>ZK loader for ZUML pages</description>
<servlet-name>zkLoader</servlet-name>
<servlet-class>org.zkoss.zk.ui.http.DHtmlLayoutServlet</servlet-class>
<!-- Must. Specifies URI of the update engine (DHtmlUpdateServlet).
It must be the same as <url-pattern> for the update engine.
-->
<init-param>
<param-name>update-uri</param-name>
<param-value>/zkau</param-value>
</init-param>
<load-on-startup>1</load-on-startup><!-- Must -->
</servlet>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zul</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zhtml</url-pattern>
</servlet-mapping>
<servlet>
<description>The asynchronous update engine for ZK</description>
<servlet-name>auEngine</servlet-name>
<servlet-class>org.zkoss.zk.au.http.DHtmlUpdateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>auEngine</servlet-name>
<url-pattern>/zkau/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
<!-- [Optional] MIME mapping -->
<mime-mapping>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
<mime-mapping>
<extension>gif</extension>
<mime-type>image/gif</mime-type>
</mime-mapping>
<mime-mapping>
<extension>htm</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>html</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jpeg</extension>
<mime-type>image/jpeg</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jpg</extension>
<mime-type>image/jpeg</mime-type>
</mime-mapping>
<mime-mapping>
<extension>js</extension>
<mime-type>text/javascript</mime-type>
</mime-mapping>
<mime-mapping>
<extension>pdf</extension>
<mime-type>application/pdf</mime-type>
</mime-mapping>
<mime-mapping>
<extension>png</extension>
<mime-type>image/png</mime-type>
</mime-mapping>
<mime-mapping>
<extension>txt</extension>
<mime-type>text/plain</mime-type>
</mime-mapping>
<mime-mapping>
<extension>xls</extension>
<mime-type>application/vnd.ms-excel</mime-type>
</mime-mapping>
<mime-mapping>
<extension>xml</extension>
<mime-type>text/xml</mime-type>
</mime-mapping>
<mime-mapping>
<extension>zhtml</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>zul</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<welcome-file-list>
<welcome-file>index.zul</welcome-file>
<welcome-file>index.zhtml</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
</web-app>

View File

@ -0,0 +1,34 @@
<zk>
<window title="List of Books" border="normal" width="600px" apply="org.zkoss.bind.BindComposer" viewModel="@id('vm') @init('com.iluwatar.model.view.viewmodel.BookViewModel')">
<vbox hflex="true">
<listbox model="@bind(vm.bookList)" selectedItem="@bind(vm.selectedBook)" height="400px" mold="paging">
<listhead>
<listheader label="Book Name"/>
<listheader label="Author"/>
</listhead>
<template name="model" var="book">
<listitem >
<listcell label="@bind(book.name)"/>
<listcell label="@bind(book.author)"/>
</listitem>
</template>
</listbox>
</vbox>
<toolbar>
        <button label="Delete" onClick="@command('deleteBook')" disabled="@load(empty vm.selectedBook)" />
    </toolbar>
<hbox style="margin-top:20px" visible="@bind(not empty vm.selectedBook)">
<vbox>
<hlayout>
Book Name : <label value="@bind(vm.selectedBook.name)" style="font-weight:bold"/>
</hlayout>
<hlayout>
Book Author : <label value="@bind(vm.selectedBook.author)" style="font-weight:bold"/>
</hlayout>
<hlayout>
Book Description : <label value="@bind(vm.selectedBook.description)" style="font-weight:bold"/>
</hlayout>
</vbox>
</hbox>
</window>
</zk>

View File

@ -0,0 +1,108 @@
/*
* The MIT License
* Copyright © 2014-2021 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.model.view.viewmodel;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.google.common.testing.EqualsTester;
class BookTest {
BookViewModel bvm;
Book testBook;
List<Book> testBookList;
Book testBookTwo;
Book testBookThree;
@BeforeEach
void setUp() {
bvm = new BookViewModel();
testBook = new Book("Head First Design Patterns: A Brain-Friendly Guide",
"Eric Freeman, Bert Bates, Kathy Sierra, Elisabeth Robson",
"Head First Design Patterns Description");
testBookList = bvm.getBookList();
testBookTwo = new Book("Head First Design Patterns: A Brain-Friendly Guide",
"Eric Freeman, Bert Bates, Kathy Sierra, Elisabeth Robson",
"Head First Design Patterns Description");
testBookThree = new Book("Design Patterns: Elements of Reusable Object-Oriented Software",
"Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides",
"Design Patterns Description");
}
@Test
void testBookModel() {
assertNotNull(testBook);
}
@Test
void testEquals() {
new EqualsTester().addEqualityGroup(testBook, testBookTwo).testEquals();
}
@Test
void testToString() {
assertThat(testBook.toString(), is(testBookTwo.toString()));
assertThat(testBook.toString(), is(not(testBookThree.toString())));
}
@Test
void testHashCode() {
assertTrue(testBook.equals(testBookTwo) && testBookTwo.equals(testBook));
assertEquals(testBook.hashCode(), testBookTwo.hashCode());
}
@Test
void testLoadData() {
assertNotNull(testBookList);
assertTrue(testBookList.get(0).toString().contains("Head First Design Patterns"));
}
@Test
void testSelectedData() {
bvm.setSelectedBook(testBook);
assertNotNull(bvm.getSelectedBook());
assertEquals(testBook.toString(), bvm.getSelectedBook().toString());
assertTrue(true, bvm.getSelectedBook().toString());
}
@Test
void testDeleteData() {
bvm.setSelectedBook(testBook);
assertNotNull(bvm.getSelectedBook());
assertTrue(testBookList.get(0).toString().contains("Head First Design Patterns"));
bvm.deleteBook();
assertNull(bvm.getSelectedBook());
assertFalse(testBookList.get(0).toString().contains("Head First Design Patterns"));
}
}

10
pom.xml
View File

@ -75,6 +75,7 @@
<directory-maven-plugin.version>0.3.1</directory-maven-plugin.version>
<license-maven-plugin.version>3.0</license-maven-plugin.version>
<urm-maven-plugin.version>1.4.8</urm-maven-plugin.version>
<commons-io.version>2.6</commons-io.version>
<!-- SonarCloud -->
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
@ -222,6 +223,7 @@
<module>special-case</module>
<module>parameter-object</module>
<module>active-object</module>
<module>model-view-viewmodel</module>
</modules>
<repositories>
@ -369,9 +371,13 @@
<version>${system-lambda.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>