Compare commits
291 Commits
Author | SHA1 | Date | |
---|---|---|---|
26d6d96f78 | |||
3cec7a9ec1 | |||
b079aec1fd | |||
8f53df91b9 | |||
709405d964 | |||
f3749a2b9d | |||
9e56e5cbc1 | |||
1698b066f3 | |||
4ed039d807 | |||
ec6d2a8ebe | |||
98c3f93e82 | |||
26fbbed62e | |||
0f9089dd62 | |||
038befea26 | |||
9daa3140e4 | |||
8458e426bc | |||
e6f84f2f41 | |||
74f3799eb4 | |||
b23d8430af | |||
cb6b0b3600 | |||
cd44ef3c81 | |||
1c2ddfad54 | |||
f36de036f6 | |||
b64262303a | |||
9d012772fd | |||
e1a2f141c5 | |||
cce104a271 | |||
16df157181 | |||
c34004bea5 | |||
3e0cfa5684 | |||
ce459e8f9f | |||
535431fac1 | |||
facb9e51a6 | |||
9eb8c30bcb | |||
fc87f8b7d3 | |||
b453753790 | |||
d2b900b524 | |||
2c8d1744df | |||
d915b66e70 | |||
328f917749 | |||
ae07423470 | |||
7add7b833c | |||
c7f9266768 | |||
0453bf9063 | |||
f9bdd58bb7 | |||
57f60c5ebf | |||
51659fe9c5 | |||
04d80f05c8 | |||
6636fb151b | |||
6a0fa747ad | |||
8b1ed95d6b | |||
6167d06dce | |||
49feead13f | |||
179a02bcdd | |||
71f61cd40e | |||
d54e29051f | |||
4456a440bc | |||
c48a1e9193 | |||
971a74e13a | |||
868e4561b5 | |||
c4dd94a019 | |||
ff579fabcf | |||
5393c96247 | |||
bae51f5803 | |||
74190e36bb | |||
6b10f4bdd1 | |||
73925cef2e | |||
987994f0fe | |||
95df47e418 | |||
afe85e22e7 | |||
4023944240 | |||
17164c282a | |||
27f58e0925 | |||
36a14778dc | |||
5e1da6361f | |||
97718846d1 | |||
bbdf1cd738 | |||
323395daaf | |||
75734a6b7d | |||
3f92b8f84e | |||
18a75c0620 | |||
9e15abbafc | |||
e9a219f643 | |||
8bf53fe91d | |||
c713dbcbf4 | |||
f3e1cd3a1d | |||
4ab46c7fcb | |||
d7893c1fc2 | |||
eddfe76a84 | |||
a386d4266d | |||
29edeabaae | |||
abcc39871b | |||
4ac6f90c96 | |||
a8d89ca861 | |||
998600f09e | |||
1e04b17a2d | |||
187b16c9e0 | |||
3b45f2cad6 | |||
65e1cae2de | |||
0b7343dd34 | |||
379a825182 | |||
522fbc035f | |||
40e5cc628a | |||
7a13012855 | |||
1c0e0cd88b | |||
3407392664 | |||
474c218f85 | |||
17ea0b17f6 | |||
7d4ccc6490 | |||
8b06ea52ab | |||
86ee59c232 | |||
6879990857 | |||
855cf75dd6 | |||
ecad864703 | |||
c3b102e547 | |||
69be74c016 | |||
3f9a5a254e | |||
05a9c030c0 | |||
c723289bbb | |||
477da92e2f | |||
ac57d67f45 | |||
960d2ea6f7 | |||
87cb33f69b | |||
915a1f3eb0 | |||
c8fd0bc23d | |||
696ed86aff | |||
e0b8f6f850 | |||
143213483c | |||
678fa93838 | |||
b2607010b4 | |||
b2dd36f607 | |||
af6973884f | |||
3894a0bb6c | |||
49f8434911 | |||
55bbb88ac9 | |||
ce88fd723e | |||
e01d640499 | |||
7fef5e4cd5 | |||
3333a2839b | |||
a60fa76fd9 | |||
565f5a4e70 | |||
b73ef6e6c5 | |||
991ba320a6 | |||
d78434fed8 | |||
f9f93695fe | |||
a367832d9e | |||
7a7ba871dc | |||
36f5947cd7 | |||
f62ae456b0 | |||
5cbf651a3e | |||
e7b119c95c | |||
ec28b1250d | |||
2dcf63c646 | |||
0805716515 | |||
9f797b3009 | |||
33a3d6fef4 | |||
dddfb52c70 | |||
9667878b5f | |||
4c4cbd41cf | |||
f7825f6c99 | |||
8960ef6111 | |||
a82000650d | |||
e9021329e1 | |||
e9a541259b | |||
94fdefee3a | |||
b61b64073a | |||
09c0891948 | |||
90570f809b | |||
55be744c4a | |||
c34975bdff | |||
ed37d5cdc7 | |||
f87754917c | |||
e046007db7 | |||
0306161380 | |||
dea2316f1f | |||
cb38501ea2 | |||
7f959ed157 | |||
6694d742a3 | |||
a20e54d0a7 | |||
e8496c5d48 | |||
3defc1b36a | |||
9677cc4eea | |||
fc690869db | |||
37c9b922a7 | |||
0824529471 | |||
235fe6a7ca | |||
5373214b70 | |||
93c54a2ee5 | |||
5a930f6a26 | |||
2a4edad23a | |||
c1ea04e002 | |||
10c0879d3b | |||
620f408688 | |||
2456b9f4b0 | |||
144db43ad4 | |||
f7c396b0fd | |||
6b4ae0d0b1 | |||
04f2be64c6 | |||
6c4de3bcef | |||
a2d155cbb9 | |||
52f09d043c | |||
11de22bf4a | |||
6614d0735e | |||
8312e09f6e | |||
176bb85f40 | |||
7e7a0c83f5 | |||
4dbf646b37 | |||
506d316529 | |||
8a9162f542 | |||
4b1650fbde | |||
d26f2620ec | |||
fb5c2a0324 | |||
7cf897a051 | |||
171c4b30b9 | |||
bf98299db2 | |||
b0f9582824 | |||
fb64d69347 | |||
4450000a83 | |||
14279278cd | |||
071cde8d70 | |||
6339e26838 | |||
5c953d7d00 | |||
51096ec445 | |||
f3f1f54ccc | |||
f58256d70a | |||
933c84ff1c | |||
3634b3338c | |||
d37922bf82 | |||
87ee97a112 | |||
c45e9a1faf | |||
390c33e36e | |||
5f90b2597a | |||
6e0bf59e5a | |||
7185830700 | |||
ec6eea61a5 | |||
89bfaf876e | |||
e289779dd3 | |||
a2a13758e0 | |||
5ed46c2c64 | |||
168c9cf3a9 | |||
0312392b3c | |||
df04e19994 | |||
8c15b89295 | |||
eeaf7e4b7c | |||
dd828bcd6c | |||
0aa84e37f2 | |||
767f41ad90 | |||
9c7ee5ed1d | |||
141d448c17 | |||
41710cbe9e | |||
04dd93f8bc | |||
624a4ef857 | |||
0453ba1315 | |||
60f07d1940 | |||
dfb43299a8 | |||
b2dd175851 | |||
31120a8fa0 | |||
ed1852a789 | |||
56ba78a5e9 | |||
522721559b | |||
f80d903cff | |||
0d4a8db114 | |||
4e236f6da8 | |||
4abef6da33 | |||
b5eca2f856 | |||
b8491436dd | |||
04891e5bf3 | |||
244e9c7caa | |||
01b85b9721 | |||
e6342d5956 | |||
e4b0153ddc | |||
8e73728fde | |||
684cad9beb | |||
a1ee8859d6 | |||
677f020813 | |||
00dcf24e16 | |||
1fb0525c6e | |||
633d3a97a0 | |||
9ee2255c1f | |||
bf700fd995 | |||
1dc143abca | |||
530b9e9662 | |||
2c9098aecc | |||
5fe9d2be6c | |||
68ed2a4726 | |||
acc2fad818 | |||
8a53a2626e | |||
e43b6f13fd | |||
4ecc337c7d | |||
3c6f7aa046 | |||
8953bfc81b |
@ -17,7 +17,7 @@ install:
|
||||
- mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -e
|
||||
|
||||
after_success:
|
||||
- mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.host.url=https://sonarqube.com -Dsonar.login=$SONAR_TOKEN
|
||||
- mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=$SONAR_TOKEN
|
||||
- bash update-ghpages.sh
|
||||
|
||||
# use latest java version available instead of travis default
|
||||
@ -36,4 +36,4 @@ notifications:
|
||||
on_failure: always # options: [always|never|change] default: always
|
||||
on_start: never # options: [always|never|change] default: always
|
||||
|
||||
sudo: required
|
||||
sudo: required
|
||||
|
@ -1,7 +1,7 @@
|
||||
# Code Coverage Report generation
|
||||
|
||||
To generate the code coverage report, execute the following command:
|
||||
> mvn clean verify
|
||||
> mvn clean verify jacoco:report
|
||||
|
||||
This will generate code coverage report in each of the modules. In order to view the same, open the following file in your browser.
|
||||
> target/site/jacoco/index.html
|
||||
|
15
PULL_REQUEST_TEMPLATE.md
Normal file
15
PULL_REQUEST_TEMPLATE.md
Normal file
@ -0,0 +1,15 @@
|
||||
|
||||
Pull request title
|
||||
|
||||
- Clearly and concisely describes what it does
|
||||
- Refer to the issue that it solves, if available
|
||||
|
||||
|
||||
Pull request description
|
||||
|
||||
- Describes the main changes that come with the pull request
|
||||
- Any relevant additional information is provided
|
||||
|
||||
|
||||
|
||||
> For detailed contributing instructions see https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute
|
@ -7,7 +7,8 @@
|
||||
[](https://travis-ci.org/iluwatar/java-design-patterns)
|
||||
[](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md)
|
||||
[](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
[](https://sonarqube.com/dashboard/index/com.iluwatar%3Ajava-design-patterns)
|
||||
[](https://sonarcloud.io/dashboard/index/com.iluwatar%3Ajava-design-patterns)
|
||||
[](https://bestpractices.coreinfrastructure.org/projects/1503)
|
||||
|
||||
# Introduction
|
||||
|
||||
|
@ -1,67 +0,0 @@
|
||||
#
|
||||
# The MIT License
|
||||
# Copyright (c) 2014-2016 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.
|
||||
#
|
||||
|
||||
import requests, glob, re, os
|
||||
|
||||
# taken from here: http://stackoverflow.com/a/13641746
|
||||
def replace(file, pattern, subst):
|
||||
# Read contents from file as a single string
|
||||
file_handle = open(file, 'r')
|
||||
file_string = file_handle.read()
|
||||
file_handle.close()
|
||||
|
||||
# Use RE package to allow for replacement (also allowing for (multiline) REGEX)
|
||||
file_string = (re.sub(pattern, subst, file_string))
|
||||
|
||||
# Write contents to file.
|
||||
# Using mode 'w' truncates the file.
|
||||
file_handle = open(file, 'w')
|
||||
file_handle.write(file_string)
|
||||
file_handle.close()
|
||||
|
||||
# list of all puml files
|
||||
fileList = glob.glob('*/etc/*.puml')
|
||||
for puml in fileList:
|
||||
pathSplit = puml.split("/")
|
||||
# parent folder
|
||||
parent = pathSplit[0]
|
||||
# individual artifact/project name
|
||||
artifact = pathSplit[2].replace(".urm.puml", "")
|
||||
print "parent: " + parent + "; artifact: " + artifact
|
||||
|
||||
# do a POST to the official plantuml hosting site with a little trick "!includeurl" and raw github content
|
||||
data = {
|
||||
'text': "!includeurl https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/" + puml
|
||||
}
|
||||
r = requests.post('http://plantuml.com/plantuml/uml', data=data)
|
||||
pumlId = r.url.replace("http://plantuml.com/plantuml/uml/", "")
|
||||
|
||||
# the only thing needed to get a png/svg/ascii from the server back
|
||||
print "Puml Server ID: " + pumlId
|
||||
|
||||
# add the id so jekyll/liquid can use it
|
||||
if (parent == artifact):
|
||||
replace("./" + parent + "/README.md", "categories:", "pumlid: {}\\ncategories:".format(pumlId))
|
||||
else:
|
||||
print "I dont want to program this, just add the following lines to the README.md file that corresponds to this puml file '" + puml + "'\npumlid: {}".format(pumlId)
|
||||
|
@ -3,7 +3,6 @@ layout: pattern
|
||||
title: Abstract Document
|
||||
folder: abstract-document
|
||||
permalink: /patterns/abstract-document/
|
||||
pumlid: PSjB3eCm34NHhPG599vtDyQn85L-ifzX-p3lxEf8Twj3MXGDQvyJMFubChxpKN767gucSq07iinEjSNDOACVNvoAUZr6MWoe3QVE_WRnxZ0Mf38b-hkIGlurX_MyehS7
|
||||
categories: Structural
|
||||
tags:
|
||||
- Java
|
||||
@ -13,8 +12,6 @@ tags:
|
||||
## Intent
|
||||
Achieve flexibility of untyped languages and keep the type-safety
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
|
||||
|
Binary file not shown.
Before Width: | Height: | Size: 15 KiB |
@ -1,58 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<class-diagram version="1.1.9" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
|
||||
realizations="true" associations="true" dependencies="false" nesting-relationships="true" router="FAN">
|
||||
<interface id="1" language="java" name="com.iluwatar.abstractdocument.Document" project="design-patterns"
|
||||
file="/design-patterns/src/com/iluwatar/abstractdocument/Document.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="249" y="405"/>
|
||||
<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="2" language="java" name="com.iluwatar.abstractdocument.AbstractDocument" project="design-patterns"
|
||||
file="/design-patterns/src/com/iluwatar/abstractdocument/AbstractDocument.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="250" y="237"/>
|
||||
<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="3" language="java" name="com.iluwatar.abstractdocument.domain.Car" project="design-patterns"
|
||||
file="/design-patterns/src/com/iluwatar/abstractdocument/domain/Car.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="108" y="75"/>
|
||||
<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="4" language="java" name="com.iluwatar.abstractdocument.domain.Part" project="design-patterns"
|
||||
file="/design-patterns/src/com/iluwatar/abstractdocument/domain/Part.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="400" y="76"/>
|
||||
<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>
|
||||
<generalization id="5">
|
||||
<end type="SOURCE" refId="4"/>
|
||||
<end type="TARGET" refId="2"/>
|
||||
</generalization>
|
||||
<realization id="6">
|
||||
<end type="SOURCE" refId="2"/>
|
||||
<end type="TARGET" refId="1"/>
|
||||
</realization>
|
||||
<generalization id="7">
|
||||
<end type="SOURCE" refId="3"/>
|
||||
<end type="TARGET" refId="2"/>
|
||||
</generalization>
|
||||
<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.
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 94 KiB |
@ -1,91 +1,137 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<class-diagram version="1.1.9" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
|
||||
realizations="true" associations="true" dependencies="false" nesting-relationships="true" router="FAN">
|
||||
<interface id="1" language="java" name="com.iluwatar.abstractdocument.Document" project="design-patterns"
|
||||
file="/design-patterns/src/com/iluwatar/abstractdocument/Document.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="341" y="376"/>
|
||||
<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>
|
||||
<interface id="2" language="java" name="com.iluwatar.abstractdocument.domain.HasModel" project="design-patterns"
|
||||
file="/design-patterns/src/com/iluwatar/abstractdocument/domain/HasModel.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="81" width="173" x="41" y="194"/>
|
||||
<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>
|
||||
<interface id="3" language="java" name="com.iluwatar.abstractdocument.domain.HasPrice" project="design-patterns"
|
||||
file="/design-patterns/src/com/iluwatar/abstractdocument/domain/HasPrice.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="81" width="175" x="254" y="194"/>
|
||||
<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>
|
||||
<interface id="4" language="java" name="com.iluwatar.abstractdocument.domain.HasParts" project="design-patterns"
|
||||
file="/design-patterns/src/com/iluwatar/abstractdocument/domain/HasParts.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="81" width="173" x="469" y="194"/>
|
||||
<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.abstractdocument.domain.Car" project="design-patterns"
|
||||
file="/design-patterns/src/com/iluwatar/abstractdocument/domain/Car.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="99" width="173" x="254" y="37"/>
|
||||
<class-diagram version="1.2.2" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
|
||||
associations="true" dependencies="false" nesting-relationships="true" router="FAN">
|
||||
<class id="1" language="java" name="com.iluwatar.abstractdocument.AbstractDocument" project="abstract-document"
|
||||
file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/AbstractDocument.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="659" y="286"/>
|
||||
<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.abstractdocument.domain.Part" project="design-patterns"
|
||||
file="/design-patterns/src/com/iluwatar/abstractdocument/domain/Part.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="99" width="173" x="41" y="37"/>
|
||||
<interface id="2" language="java" name="com.iluwatar.abstractdocument.Document" project="abstract-document"
|
||||
file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/Document.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="562" y="27"/>
|
||||
<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="3" language="java" name="com.iluwatar.abstractdocument.domain.Car" project="abstract-document"
|
||||
file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Car.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="348" y="737"/>
|
||||
<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="7">
|
||||
<end type="SOURCE" refId="5"/>
|
||||
<end type="TARGET" refId="2"/>
|
||||
<class id="4" language="java" name="com.iluwatar.abstractdocument.domain.Part" project="abstract-document"
|
||||
file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Part.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="760" y="746"/>
|
||||
<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>
|
||||
<interface id="5" language="java" name="com.iluwatar.abstractdocument.domain.HasModel" project="abstract-document"
|
||||
file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasModel.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="355" y="297"/>
|
||||
<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>
|
||||
<interface id="6" language="java" name="com.iluwatar.abstractdocument.domain.HasParts" project="abstract-document"
|
||||
file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasParts.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="109" y="297"/>
|
||||
<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>
|
||||
<interface id="7" language="java" name="com.iluwatar.abstractdocument.domain.HasPrice" project="abstract-document"
|
||||
file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasPrice.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="1008" y="283"/>
|
||||
<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>
|
||||
<interface id="8" language="java" name="com.iluwatar.abstractdocument.domain.HasType" project="abstract-document"
|
||||
file="/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasType.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="1257" y="277"/>
|
||||
<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>
|
||||
<realization id="9">
|
||||
<end type="SOURCE" refId="4"/>
|
||||
<end type="TARGET" refId="8"/>
|
||||
</realization>
|
||||
<realization id="8">
|
||||
<realization id="10">
|
||||
<end type="SOURCE" refId="3"/>
|
||||
<end type="TARGET" refId="7"/>
|
||||
</realization>
|
||||
<generalization id="11">
|
||||
<end type="SOURCE" refId="6"/>
|
||||
<end type="TARGET" refId="2"/>
|
||||
</realization>
|
||||
<generalization id="9">
|
||||
<end type="SOURCE" refId="2"/>
|
||||
<end type="TARGET" refId="1"/>
|
||||
</generalization>
|
||||
<realization id="10">
|
||||
<end type="SOURCE" refId="5"/>
|
||||
<end type="TARGET" refId="3"/>
|
||||
<realization id="12">
|
||||
<end type="SOURCE" refId="4"/>
|
||||
<end type="TARGET" refId="5"/>
|
||||
</realization>
|
||||
<realization id="11">
|
||||
<end type="SOURCE" refId="5"/>
|
||||
<end type="TARGET" refId="4"/>
|
||||
<realization id="13">
|
||||
<end type="SOURCE" refId="4"/>
|
||||
<end type="TARGET" refId="7"/>
|
||||
</realization>
|
||||
<generalization id="12">
|
||||
<generalization id="14">
|
||||
<end type="SOURCE" refId="3"/>
|
||||
<end type="TARGET" refId="1"/>
|
||||
</generalization>
|
||||
<generalization id="13">
|
||||
<realization id="15">
|
||||
<end type="SOURCE" refId="3"/>
|
||||
<end type="TARGET" refId="6"/>
|
||||
</realization>
|
||||
<generalization id="16">
|
||||
<end type="SOURCE" refId="8"/>
|
||||
<end type="TARGET" refId="2"/>
|
||||
</generalization>
|
||||
<generalization id="17">
|
||||
<end type="SOURCE" refId="7"/>
|
||||
<end type="TARGET" refId="2"/>
|
||||
</generalization>
|
||||
<realization id="18">
|
||||
<end type="SOURCE" refId="3"/>
|
||||
<end type="TARGET" refId="5"/>
|
||||
</realization>
|
||||
<generalization id="19">
|
||||
<end type="SOURCE" refId="4"/>
|
||||
<end type="TARGET" refId="1"/>
|
||||
</generalization>
|
||||
<realization id="14">
|
||||
<end type="SOURCE" refId="6"/>
|
||||
<end type="TARGET" refId="3"/>
|
||||
<generalization id="20">
|
||||
<end type="SOURCE" refId="5"/>
|
||||
<end type="TARGET" refId="2"/>
|
||||
</generalization>
|
||||
<realization id="21">
|
||||
<end type="SOURCE" refId="1"/>
|
||||
<end type="TARGET" refId="2"/>
|
||||
</realization>
|
||||
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
|
@ -1,59 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.abstractdocument.domain {
|
||||
class Car {
|
||||
+ Car(properties : Map<String, Object>)
|
||||
}
|
||||
interface HasModel {
|
||||
+ PROPERTY : String {static}
|
||||
+ getModel() : Optional<String>
|
||||
}
|
||||
interface HasParts {
|
||||
+ PROPERTY : String {static}
|
||||
+ getParts() : Stream<Part>
|
||||
}
|
||||
interface HasPrice {
|
||||
+ PROPERTY : String {static}
|
||||
+ getPrice() : Optional<Number>
|
||||
}
|
||||
interface HasType {
|
||||
+ PROPERTY : String {static}
|
||||
+ getType() : Optional<String>
|
||||
}
|
||||
class Part {
|
||||
+ Part(properties : Map<String, Object>)
|
||||
}
|
||||
}
|
||||
package com.iluwatar.abstractdocument {
|
||||
abstract class AbstractDocument {
|
||||
- properties : Map<String, Object>
|
||||
# AbstractDocument(properties : Map<String, Object>)
|
||||
+ children(key : String, constructor : Function<Map<String, Object>, T>) : Stream<T>
|
||||
+ get(key : String) : Object
|
||||
+ put(key : String, value : Object)
|
||||
+ toString() : String
|
||||
}
|
||||
class App {
|
||||
- LOGGER : Logger {static}
|
||||
+ App()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
interface Document {
|
||||
+ children(String, Function<Map<String, Object>, T>) : Stream<T> {abstract}
|
||||
+ get(String) : Object {abstract}
|
||||
+ put(String, Object) {abstract}
|
||||
}
|
||||
}
|
||||
AbstractDocument ..|> Document
|
||||
Car ..|> HasModel
|
||||
Car ..|> HasPrice
|
||||
Car ..|> HasParts
|
||||
Car --|> AbstractDocument
|
||||
HasModel --|> Document
|
||||
HasParts --|> Document
|
||||
HasPrice --|> Document
|
||||
HasType --|> Document
|
||||
Part ..|> HasType
|
||||
Part ..|> HasModel
|
||||
Part ..|> HasPrice
|
||||
Part --|> AbstractDocument
|
||||
@enduml
|
@ -29,13 +29,18 @@
|
||||
<parent>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<artifactId>abstract-document</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
@ -22,7 +22,7 @@
|
||||
*/
|
||||
package com.iluwatar.abstractdocument;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
@ -30,8 +30,8 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static junit.framework.TestCase.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
/**
|
||||
* AbstractDocument test class
|
||||
|
@ -22,7 +22,7 @@
|
||||
*/
|
||||
package com.iluwatar.abstractdocument;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Simple App test
|
||||
|
@ -28,13 +28,13 @@ import com.iluwatar.abstractdocument.domain.HasParts;
|
||||
import com.iluwatar.abstractdocument.domain.HasPrice;
|
||||
import com.iluwatar.abstractdocument.domain.HasType;
|
||||
import com.iluwatar.abstractdocument.domain.Part;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Test for Part and Car
|
||||
|
@ -3,7 +3,6 @@ layout: pattern
|
||||
title: Abstract Factory
|
||||
folder: abstract-factory
|
||||
permalink: /patterns/abstract-factory/
|
||||
pumlid: PSZB3OD034NHLa81Czwd6sCC39gVxEUWT1_ssLmTtQLqgR5fM7sTmFGtaV6TZu8prd0r6HtQaMKqAZLk1XjT_E6qgPUZfyc0MdTgx0-8LuUn8ErFXdr98NypXxKyezKV
|
||||
categories: Creational
|
||||
tags:
|
||||
- Java
|
||||
@ -35,7 +34,7 @@ Wikipedia says
|
||||
|
||||
Translating the kingdom example above. First of all we have some interfaces and implementation for the objects in the kingdom
|
||||
|
||||
```
|
||||
```java
|
||||
public interface Castle {
|
||||
String getDescription();
|
||||
}
|
||||
@ -75,7 +74,7 @@ public class ElfArmy implements Army {
|
||||
|
||||
Then we have the abstraction and implementations for the kingdom factory
|
||||
|
||||
```
|
||||
```java
|
||||
public interface KingdomFactory {
|
||||
Castle createCastle();
|
||||
King createKing();
|
||||
@ -109,7 +108,7 @@ public class OrcKingdomFactory implements KingdomFactory {
|
||||
|
||||
Now we have our abstract factory that lets us make family of related objects i.e. Elven kingdom factory creates Elven castle, king and army etc.
|
||||
|
||||
```
|
||||
```java
|
||||
KingdomFactory factory = new ElfKingdomFactory();
|
||||
Castle castle = factory.createCastle();
|
||||
King king = factory.createKing();
|
||||
@ -120,6 +119,45 @@ king.getDescription(); // Output: This is the Elven king!
|
||||
army.getDescription(); // Output: This is the Elven Army!
|
||||
```
|
||||
|
||||
Now, we can design a factory for our different kingdom factories. In this example, we created FactoryMaker, responsible for returning an instance of either ElfKingdomFactory or OrcKingdomFactory.
|
||||
The client can use FactoryMaker to create the desired concrete factory which, in turn, will produce different concrete objects (Army, King, Castle).
|
||||
In this example, we also used an enum to parameterize which type of kingdom factory the client will ask for.
|
||||
|
||||
```java
|
||||
public static class FactoryMaker {
|
||||
|
||||
public enum KingdomType {
|
||||
ELF, ORC
|
||||
}
|
||||
|
||||
public static KingdomFactory makeFactory(KingdomType type) {
|
||||
switch (type) {
|
||||
case ELF:
|
||||
return new ElfKingdomFactory();
|
||||
case ORC:
|
||||
return new OrcKingdomFactory();
|
||||
default:
|
||||
throw new IllegalArgumentException("KingdomType not supported.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
App app = new App();
|
||||
|
||||
LOGGER.info("Elf Kingdom");
|
||||
app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF));
|
||||
LOGGER.info(app.getArmy().getDescription());
|
||||
LOGGER.info(app.getCastle().getDescription());
|
||||
LOGGER.info(app.getKing().getDescription());
|
||||
|
||||
LOGGER.info("Orc Kingdom");
|
||||
app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC));
|
||||
-- similar use of the orc factory
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Applicability
|
||||
Use the Abstract Factory pattern when
|
||||
|
||||
@ -141,6 +179,15 @@ Use the Abstract Factory pattern when
|
||||
|
||||
* Dependency injection in java hides the service class dependencies that can lead to runtime errors that would have been caught at compile time.
|
||||
|
||||
|
||||
## Tutorial
|
||||
* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java)
|
||||
|
||||
## Presentations
|
||||
|
||||
* [Abstract Factory Pattern](etc/presentation.html)
|
||||
|
||||
|
||||
## Real world examples
|
||||
|
||||
* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html)
|
||||
|
BIN
abstract-factory/etc/diagram1.png
Normal file
BIN
abstract-factory/etc/diagram1.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 57 KiB |
BIN
abstract-factory/etc/diagram2.png
Normal file
BIN
abstract-factory/etc/diagram2.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 26 KiB |
190
abstract-factory/etc/presentation.html
Normal file
190
abstract-factory/etc/presentation.html
Normal file
@ -0,0 +1,190 @@
|
||||
<!--
|
||||
|
||||
The MIT License
|
||||
Copyright (c) 2017 Rodolfo Forte
|
||||
|
||||
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.
|
||||
|
||||
-->
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Design Patterns - Abstract Factory Presentation</title>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
@import url(https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz);
|
||||
@import url(https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic);
|
||||
@import url(https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic);
|
||||
|
||||
body { font-family: 'Droid Serif'; }
|
||||
h1, h2, h3 {
|
||||
font-family: 'Yanone Kaffeesatz';
|
||||
font-weight: normal;
|
||||
}
|
||||
.remark-code, .remark-inline-code { font-family: 'Ubuntu Mono'; }
|
||||
|
||||
blockquote {
|
||||
border-left: 0.3em solid rgba(0,0,0,0.5);
|
||||
padding: 0 15px;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
img {
|
||||
max-width:100%;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<textarea id="source">
|
||||
|
||||
class: center, middle
|
||||
|
||||
# Abstract Factory
|
||||
|
||||
---
|
||||
|
||||
# Also known as
|
||||
|
||||
* Kit
|
||||
|
||||
---
|
||||
|
||||
# Intent
|
||||
|
||||
* Provide an interface for creating families of related or dependent objects without specifying their concrete classes
|
||||
|
||||
---
|
||||
|
||||
# Explanation
|
||||
|
||||
* [Wikipedia](https://en.wikipedia.org/wiki/Abstract_factory_pattern) says:
|
||||
> "The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes"
|
||||
|
||||
<br />
|
||||
|
||||
* In plain words:
|
||||
* A factory that groups individual but related/dependent factories together without specifying their concrete classes;
|
||||
* A factory of factories;
|
||||
|
||||
---
|
||||
|
||||
# Example
|
||||
|
||||
* In a factory that creates kingdoms, we need objects with common theme:
|
||||
|
||||
* Elven kingdom needs an Elven king, Elven castle and Elven army;
|
||||
|
||||
* Orcish kingdom needs an Orcish king, Orcish castle and Orcish army;
|
||||
|
||||
<br />
|
||||
|
||||
* There is a dependency between the objects in the kingdom;
|
||||
|
||||
---
|
||||
|
||||
# Diagram
|
||||
|
||||
* Based on the kingdom example, the diagram below showcases the different concrete factories and their concrete products:
|
||||
|
||||
.center[]
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Diagram
|
||||
|
||||
* The class diagram below showcases the factory of factories;
|
||||
|
||||
* At runtime, we can define which Kingdom type is needed and pass it as a parameter to define which concrete KingdomFactory to instantiate;
|
||||
|
||||
* The concrete factory returned will then be able to produce the related objects of the specified type;
|
||||
|
||||
.center[]
|
||||
|
||||
---
|
||||
|
||||
# Applicability
|
||||
|
||||
Use the Abstract Factory pattern when:
|
||||
|
||||
* A system should be independent of how its products are created, composed and represented;
|
||||
|
||||
* A system should be configured with one of multiple families of products;
|
||||
|
||||
* A family of related product objects is designed to be used together, and you need to enforce this constraint;
|
||||
|
||||
* You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations;
|
||||
|
||||
---
|
||||
|
||||
# Applicability
|
||||
|
||||
Use the Abstract Factory pattern when:
|
||||
|
||||
* The lifetime of the dependency is conceptually shorter than the lifetime of the consumer;
|
||||
|
||||
* You need a run-time value to construct a particular dependency;
|
||||
|
||||
* You want to decide which product to call from a family at runtime;
|
||||
|
||||
* You need to supply one or more parameters only known at run-time before you can resolve a dependency;
|
||||
|
||||
---
|
||||
|
||||
#Use Cases
|
||||
|
||||
* Selecting to call the appropriate implementation of FileSystemAcmeService or DatabaseAcmeService or NetworkAcmeService at runtime;
|
||||
* Unit test case writing becomes much easier;
|
||||
|
||||
---
|
||||
|
||||
# Consequences
|
||||
|
||||
* Dependency injection in java hides the service class dependencies that can lead to runtime errors that would have been caught at compile time
|
||||
|
||||
---
|
||||
|
||||
# Real world examples
|
||||
|
||||
[javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html)
|
||||
|
||||
[javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--)
|
||||
|
||||
[javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--)
|
||||
|
||||
---
|
||||
|
||||
# Credits
|
||||
|
||||
* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612)
|
||||
|
||||
---
|
||||
|
||||
# Tutorials
|
||||
|
||||
* Source code http://java-design-patterns.com/patterns/abstract-factory/
|
||||
|
||||
</textarea>
|
||||
<script src="https://gnab.github.io/remark/downloads/remark-latest.min.js">
|
||||
</script>
|
||||
<script>
|
||||
var slideshow = remark.create();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
@ -29,13 +29,18 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<artifactId>abstract-factory</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
@ -25,6 +25,8 @@ package com.iluwatar.abstractfactory;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.iluwatar.abstractfactory.App.FactoryMaker.KingdomType;
|
||||
|
||||
/**
|
||||
*
|
||||
* The Abstract Factory pattern provides a way to encapsulate a group of individual factories that have a common theme
|
||||
@ -56,7 +58,7 @@ public class App {
|
||||
setCastle(factory.createCastle());
|
||||
setArmy(factory.createArmy());
|
||||
}
|
||||
|
||||
|
||||
King getKing(final KingdomFactory factory) {
|
||||
return factory.createKing();
|
||||
}
|
||||
@ -92,9 +94,36 @@ public class App {
|
||||
private void setArmy(final Army army) {
|
||||
this.army = army;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Program entry point
|
||||
* The factory of kingdom factories.
|
||||
*/
|
||||
public static class FactoryMaker {
|
||||
|
||||
/**
|
||||
* Enumeration for the different types of Kingdoms.
|
||||
*/
|
||||
public enum KingdomType {
|
||||
ELF, ORC
|
||||
}
|
||||
|
||||
/**
|
||||
* The factory method to create KingdomFactory concrete objects.
|
||||
*/
|
||||
public static KingdomFactory makeFactory(KingdomType type) {
|
||||
switch (type) {
|
||||
case ELF:
|
||||
return new ElfKingdomFactory();
|
||||
case ORC:
|
||||
return new OrcKingdomFactory();
|
||||
default:
|
||||
throw new IllegalArgumentException("KingdomType not supported.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Program entry point.
|
||||
*
|
||||
* @param args
|
||||
* command line args
|
||||
@ -104,17 +133,15 @@ public class App {
|
||||
App app = new App();
|
||||
|
||||
LOGGER.info("Elf Kingdom");
|
||||
app.createKingdom(new ElfKingdomFactory());
|
||||
app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF));
|
||||
LOGGER.info(app.getArmy().getDescription());
|
||||
LOGGER.info(app.getCastle().getDescription());
|
||||
LOGGER.info(app.getKing().getDescription());
|
||||
|
||||
LOGGER.info("Orc Kingdom");
|
||||
app.createKingdom(new OrcKingdomFactory());
|
||||
app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC));
|
||||
LOGGER.info(app.getArmy().getDescription());
|
||||
LOGGER.info(app.getCastle().getDescription());
|
||||
LOGGER.info(app.getKing().getDescription());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -22,11 +22,14 @@
|
||||
*/
|
||||
package com.iluwatar.abstractfactory;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import com.iluwatar.abstractfactory.App.FactoryMaker;
|
||||
import com.iluwatar.abstractfactory.App.FactoryMaker.KingdomType;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Test for abstract factory
|
||||
@ -37,10 +40,10 @@ public class AbstractFactoryTest {
|
||||
private KingdomFactory elfFactory;
|
||||
private KingdomFactory orcFactory;
|
||||
|
||||
@Before
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
elfFactory = new ElfKingdomFactory();
|
||||
orcFactory = new OrcKingdomFactory();
|
||||
elfFactory = FactoryMaker.makeFactory(KingdomType.ELF);
|
||||
orcFactory = FactoryMaker.makeFactory(KingdomType.ORC);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -22,7 +22,7 @@
|
||||
*/
|
||||
package com.iluwatar.abstractfactory;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
|
39
acyclic-visitor/README.md
Normal file
39
acyclic-visitor/README.md
Normal file
@ -0,0 +1,39 @@
|
||||
---
|
||||
layout: pattern
|
||||
title: Acyclic Visitor
|
||||
folder: acyclic-visitor
|
||||
permalink: /patterns/acyclic-visitor/
|
||||
categories: Behavioral
|
||||
tags:
|
||||
- Java
|
||||
- Difficulty-Intermediate
|
||||
---
|
||||
|
||||

|
||||
|
||||
## Intent
|
||||
Allow new functions to be added to existing class hierarchies without affecting those hierarchies, and without creating the troublesome dependency cycles that are inherent to the GOF VISITOR Pattern.
|
||||
|
||||
## Applicability
|
||||
This pattern can be used:
|
||||
* When you need to add a new function to an existing hierarchy without the need to alter or affect that hierarchy.
|
||||
* When there are functions that operate upon a hierarchy, but which do not belong in the hierarchy itself. e.g. the ConfigureForDOS / ConfigureForUnix / ConfigureForX issue.
|
||||
* When you need to perform very different operations on an object depending upon its type.
|
||||
* When the visited class hierarchy will be frequently extended with new derivatives of the Element class.
|
||||
* When the recompilation, relinking, retesting or redistribution of the derivatives of Element is very expensive.
|
||||
|
||||
## Consequences
|
||||
The good:
|
||||
* No dependency cycles between class hierarchies.
|
||||
* No need to recompile all the visitors if a new one is added.
|
||||
* Does not cause compilation failure in existing visitors if class hierarchy has a new member.
|
||||
|
||||
The bad:
|
||||
* Violates the principle of least surprise or Liskov's Substitution principle by showing that it can accept all visitors but actually only being interested in particular visitors.
|
||||
* Parallel hierarchy of visitors has to be created for all members in visitable class hierarchy.
|
||||
|
||||
## Related patterns
|
||||
* [Visitor Pattern](../visitor/README.md)
|
||||
|
||||
## Credits
|
||||
* [Acyclic Visitor](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf)
|
115
acyclic-visitor/etc/Acyclic Visitor.ucls
Normal file
115
acyclic-visitor/etc/Acyclic Visitor.ucls
Normal file
@ -0,0 +1,115 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<class-diagram version="1.2.2" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
|
||||
associations="true" dependencies="false" nesting-relationships="true" router="FAN">
|
||||
<interface id="1" language="java" name="com.iluwatar.acyclicvisitor.ModemVisitor" project="acyclic-visitor"
|
||||
file="/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ModemVisitor.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="860" y="67"/>
|
||||
<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="2" language="java" name="com.iluwatar.acyclicvisitor.Modem" project="acyclic-visitor"
|
||||
file="/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Modem.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="327" y="77"/>
|
||||
<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="3" language="java" name="com.iluwatar.acyclicvisitor.ConfigureForUnixVisitor" project="acyclic-visitor"
|
||||
file="/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="124" width="196" x="647" y="225"/>
|
||||
<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="4" language="java" name="com.iluwatar.acyclicvisitor.Zoom" project="acyclic-visitor"
|
||||
file="/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="203" y="305"/>
|
||||
<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>
|
||||
<interface id="5" language="java" name="com.iluwatar.acyclicvisitor.HayesVisitor" project="acyclic-visitor"
|
||||
file="/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/HayesVisitor.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="1019" y="468"/>
|
||||
<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>
|
||||
<interface id="6" language="java" name="com.iluwatar.acyclicvisitor.ZoomVisitor" project="acyclic-visitor"
|
||||
file="/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="758" y="467"/>
|
||||
<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="7" language="java" name="com.iluwatar.acyclicvisitor.Hayes" project="acyclic-visitor"
|
||||
file="/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="479" y="307"/>
|
||||
<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="8" language="java" name="com.iluwatar.acyclicvisitor.ConfigureForDosVisitor" project="acyclic-visitor"
|
||||
file="/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForDosVisitor.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="142" width="192" x="883" y="225"/>
|
||||
<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>
|
||||
<generalization id="9">
|
||||
<end type="SOURCE" refId="7"/>
|
||||
<end type="TARGET" refId="2"/>
|
||||
</generalization>
|
||||
<realization id="10">
|
||||
<end type="SOURCE" refId="8"/>
|
||||
<end type="TARGET" refId="6"/>
|
||||
</realization>
|
||||
<realization id="11">
|
||||
<end type="SOURCE" refId="8"/>
|
||||
<end type="TARGET" refId="5"/>
|
||||
</realization>
|
||||
<realization id="12">
|
||||
<end type="SOURCE" refId="3"/>
|
||||
<end type="TARGET" refId="6"/>
|
||||
</realization>
|
||||
<realization id="13">
|
||||
<end type="SOURCE" refId="3"/>
|
||||
<end type="TARGET" refId="1"/>
|
||||
</realization>
|
||||
<realization id="14">
|
||||
<end type="SOURCE" refId="8"/>
|
||||
<end type="TARGET" refId="1"/>
|
||||
</realization>
|
||||
<generalization id="15">
|
||||
<end type="SOURCE" refId="4"/>
|
||||
<end type="TARGET" refId="2"/>
|
||||
</generalization>
|
||||
<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>
|
BIN
acyclic-visitor/etc/acyclic-visitor.png
Normal file
BIN
acyclic-visitor/etc/acyclic-visitor.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 26 KiB |
76
acyclic-visitor/pom.xml
Normal file
76
acyclic-visitor/pom.xml
Normal file
@ -0,0 +1,76 @@
|
||||
<!--
|
||||
|
||||
The MIT License
|
||||
Copyright (c) 2014 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.
|
||||
|
||||
-->
|
||||
<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>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>acyclic-visitor</artifactId>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.assertj/assertj-core -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.9.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/uk.org.lidalia/slf4j-test -->
|
||||
<dependency>
|
||||
<groupId>uk.org.lidalia</groupId>
|
||||
<artifactId>slf4j-test</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-all</artifactId>
|
||||
<version>1.9.5</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
@ -0,0 +1,31 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
/**
|
||||
* All ModemVisitor interface extends all visitor interfaces. This interface
|
||||
* provides ease of use when a visitor needs to visit all modem types.
|
||||
*/
|
||||
public interface AllModemVisitor extends ZoomVisitor, HayesVisitor{
|
||||
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
/**
|
||||
* The Acyclic Visitor pattern allows new functions to be added to existing class
|
||||
* hierarchies without affecting those hierarchies, and without creating the dependency
|
||||
* cycles that are inherent to the GoF Visitor pattern, by making the Visitor base class
|
||||
* degenerate
|
||||
* <p>
|
||||
* In this example the visitor base class is {@link ModemVisitor}. The base class of the
|
||||
* visited hierarchy is {@link Modem} and has two children {@link Hayes} and {@link Zoom}
|
||||
* each one having its own visitor interface {@link HayesVisitor} and {@link ZoomVisitor}
|
||||
* respectively. {@link ConfigureForUnixVisitor} and {@link ConfigureForDosVisitor}
|
||||
* implement each derivative's visit method only if it is required
|
||||
*/
|
||||
public class App {
|
||||
|
||||
/**
|
||||
* Program's entry point
|
||||
*/
|
||||
|
||||
public static void main(String[] args) {
|
||||
ConfigureForUnixVisitor conUnix = new ConfigureForUnixVisitor();
|
||||
ConfigureForDosVisitor conDos = new ConfigureForDosVisitor();
|
||||
|
||||
Zoom zoom = new Zoom();
|
||||
Hayes hayes = new Hayes();
|
||||
|
||||
hayes.accept(conDos); // Hayes modem with Unix configurator
|
||||
zoom.accept(conDos); // Zoom modem with Dos configurator
|
||||
hayes.accept(conUnix); // Hayes modem with Unix configurator
|
||||
zoom.accept(conUnix); // Zoom modem with Unix configurator
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* ConfigureForDosVisitor class implements both zoom's and hayes' visit method
|
||||
* for Dos manufacturer
|
||||
*/
|
||||
public class ConfigureForDosVisitor implements AllModemVisitor {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigureForDosVisitor.class);
|
||||
|
||||
public void visit(Hayes hayes) {
|
||||
LOGGER.info(hayes + " used with Dos configurator.");
|
||||
}
|
||||
|
||||
public void visit(Zoom zoom) {
|
||||
LOGGER.info(zoom + " used with Dos configurator.");
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* ConfigureForUnixVisitor class implements zoom's visit method for Unix
|
||||
* manufacturer, unlike traditional visitor pattern, this class may selectively implement
|
||||
* visit for other modems.
|
||||
*/
|
||||
public class ConfigureForUnixVisitor implements ZoomVisitor {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigureForUnixVisitor.class);
|
||||
|
||||
public void visit(Zoom zoom) {
|
||||
LOGGER.info(zoom + " used with Unix configurator.");
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Hayes class implements its accept method
|
||||
*/
|
||||
public class Hayes extends Modem {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigureForDosVisitor.class);
|
||||
|
||||
/**
|
||||
* Accepts all visitors but honors only HayesVisitor
|
||||
*/
|
||||
@Override
|
||||
public void accept(ModemVisitor modemVisitor) {
|
||||
if (modemVisitor instanceof HayesVisitor) {
|
||||
((HayesVisitor) modemVisitor).visit(this);
|
||||
} else {
|
||||
LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Hayes' modem's toString
|
||||
* method
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Hayes modem";
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
/**
|
||||
* HayesVisitor interface
|
||||
*/
|
||||
public interface HayesVisitor extends ModemVisitor {
|
||||
void visit(Hayes hayes);
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
/**
|
||||
* Modem abstract class
|
||||
*/
|
||||
public abstract class Modem {
|
||||
public abstract void accept(ModemVisitor modemVisitor);
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
/**
|
||||
* ModemVisitor interface does not contain any visit methods so that it does not
|
||||
* depend on the visited hierarchy. Each derivative's visit method is declared in
|
||||
* its own visitor interface
|
||||
*/
|
||||
public interface ModemVisitor {
|
||||
// Visitor is a degenerate base class for all visitors.
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Zoom class implements its accept method
|
||||
*/
|
||||
public class Zoom extends Modem {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigureForDosVisitor.class);
|
||||
|
||||
/**
|
||||
* Accepts all visitors but honors only ZoomVisitor
|
||||
*/
|
||||
@Override
|
||||
public void accept(ModemVisitor modemVisitor) {
|
||||
if (modemVisitor instanceof ZoomVisitor) {
|
||||
((ZoomVisitor) modemVisitor).visit(this);
|
||||
} else {
|
||||
LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Zoom modem's toString
|
||||
* method
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Zoom modem";
|
||||
}
|
||||
}
|
@ -20,16 +20,11 @@
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.iterator;
|
||||
package com.iluwatar.acyclicvisitor;
|
||||
|
||||
/**
|
||||
*
|
||||
* ItemIterator interface.
|
||||
*
|
||||
* ZoomVisitor interface
|
||||
*/
|
||||
public interface ItemIterator {
|
||||
|
||||
boolean hasNext();
|
||||
|
||||
Item next();
|
||||
public interface ZoomVisitor extends ModemVisitor {
|
||||
void visit(Zoom zoom);
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.iluwatar.acyclicvisitor.App;
|
||||
|
||||
/**
|
||||
* Tests that the Acyclic Visitor example runs without errors.
|
||||
*/
|
||||
public class AppTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
}
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.groups.Tuple.tuple;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static uk.org.lidalia.slf4jext.Level.INFO;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.iluwatar.acyclicvisitor.ConfigureForDosVisitor;
|
||||
import com.iluwatar.acyclicvisitor.Hayes;
|
||||
import com.iluwatar.acyclicvisitor.HayesVisitor;
|
||||
import com.iluwatar.acyclicvisitor.Zoom;
|
||||
import com.iluwatar.acyclicvisitor.ZoomVisitor;
|
||||
|
||||
import uk.org.lidalia.slf4jtest.TestLogger;
|
||||
import uk.org.lidalia.slf4jtest.TestLoggerFactory;
|
||||
|
||||
/**
|
||||
* ConfigureForDosVisitor test class
|
||||
*/
|
||||
public class ConfigureForDosVisitorTest {
|
||||
|
||||
TestLogger logger = TestLoggerFactory.getTestLogger(ConfigureForDosVisitor.class);
|
||||
|
||||
@Test
|
||||
public void testVisitForZoom() {
|
||||
ConfigureForDosVisitor conDos = new ConfigureForDosVisitor();
|
||||
Zoom zoom = new Zoom();
|
||||
|
||||
conDos.visit(zoom);
|
||||
|
||||
assertThat(logger.getLoggingEvents()).extracting("level", "message").contains(
|
||||
tuple(INFO, zoom + " used with Dos configurator."));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVisitForHayes() {
|
||||
ConfigureForDosVisitor conDos = new ConfigureForDosVisitor();
|
||||
Hayes hayes = new Hayes();
|
||||
|
||||
conDos.visit(hayes);
|
||||
|
||||
assertThat(logger.getLoggingEvents()).extracting("level", "message").contains(
|
||||
tuple(INFO, hayes + " used with Dos configurator."));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
public void clearLoggers() {
|
||||
TestLoggerFactory.clear();
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.groups.Tuple.tuple;
|
||||
import static uk.org.lidalia.slf4jext.Level.INFO;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import uk.org.lidalia.slf4jtest.TestLogger;
|
||||
import uk.org.lidalia.slf4jtest.TestLoggerFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.iluwatar.acyclicvisitor.ConfigureForUnixVisitor;
|
||||
import com.iluwatar.acyclicvisitor.Hayes;
|
||||
import com.iluwatar.acyclicvisitor.HayesVisitor;
|
||||
import com.iluwatar.acyclicvisitor.Zoom;
|
||||
import com.iluwatar.acyclicvisitor.ZoomVisitor;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
|
||||
/**
|
||||
* ConfigureForUnixVisitor test class
|
||||
*/
|
||||
public class ConfigureForUnixVisitorTest {
|
||||
|
||||
TestLogger logger = TestLoggerFactory.getTestLogger(ConfigureForUnixVisitor.class);
|
||||
|
||||
@AfterEach
|
||||
public void clearLoggers() {
|
||||
TestLoggerFactory.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVisitForZoom() {
|
||||
ConfigureForUnixVisitor conUnix = new ConfigureForUnixVisitor();
|
||||
Zoom zoom = new Zoom();
|
||||
|
||||
conUnix.visit(zoom);
|
||||
|
||||
assertThat(logger.getLoggingEvents()).extracting("level", "message").contains(
|
||||
tuple(INFO, zoom + " used with Unix configurator."));
|
||||
}
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.iluwatar.acyclicvisitor.ConfigureForDosVisitor;
|
||||
import com.iluwatar.acyclicvisitor.ConfigureForUnixVisitor;
|
||||
import com.iluwatar.acyclicvisitor.Hayes;
|
||||
import com.iluwatar.acyclicvisitor.HayesVisitor;
|
||||
|
||||
/**
|
||||
* Hayes test class
|
||||
*/
|
||||
public class HayesTest {
|
||||
|
||||
@Test
|
||||
public void testAcceptForDos() {
|
||||
Hayes hayes = new Hayes();
|
||||
ConfigureForDosVisitor mockVisitor = mock(ConfigureForDosVisitor.class);
|
||||
|
||||
hayes.accept(mockVisitor);
|
||||
verify((HayesVisitor)mockVisitor).visit(eq(hayes));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAcceptForUnix() {
|
||||
Hayes hayes = new Hayes();
|
||||
ConfigureForUnixVisitor mockVisitor = mock(ConfigureForUnixVisitor.class);
|
||||
|
||||
hayes.accept(mockVisitor);
|
||||
|
||||
verifyZeroInteractions(mockVisitor);
|
||||
}
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.acyclicvisitor;
|
||||
|
||||
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.iluwatar.acyclicvisitor.ConfigureForDosVisitor;
|
||||
import com.iluwatar.acyclicvisitor.ConfigureForUnixVisitor;
|
||||
import com.iluwatar.acyclicvisitor.Zoom;
|
||||
import com.iluwatar.acyclicvisitor.ZoomVisitor;
|
||||
|
||||
/**
|
||||
* Zoom test class
|
||||
*/
|
||||
public class ZoomTest {
|
||||
|
||||
@Test
|
||||
public void testAcceptForDos() {
|
||||
Zoom zoom = new Zoom();
|
||||
ConfigureForDosVisitor mockVisitor = mock(ConfigureForDosVisitor.class);
|
||||
|
||||
zoom.accept(mockVisitor);
|
||||
verify((ZoomVisitor)mockVisitor).visit(eq(zoom));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAcceptForUnix() {
|
||||
Zoom zoom = new Zoom();
|
||||
ConfigureForUnixVisitor mockVisitor = mock(ConfigureForUnixVisitor.class);
|
||||
|
||||
zoom.accept(mockVisitor);
|
||||
verify((ZoomVisitor)mockVisitor).visit(eq(zoom));
|
||||
}
|
||||
}
|
@ -3,7 +3,6 @@ layout: pattern
|
||||
title: Adapter
|
||||
folder: adapter
|
||||
permalink: /patterns/adapter/
|
||||
pumlid: DSR14S8m30J0Lg20M7-wEMnDOiPMFDA9j0yyUEtUkzMHJTF7xI1NF4GSLzaxZtncgDVJgCPIpobzv0N2vOKtjgRHTziMI7KBcOXl10thfxB-Nz9dMJd71m00
|
||||
categories: Structural
|
||||
tags:
|
||||
- Java
|
||||
@ -41,7 +40,7 @@ Consider a captain that can only use rowing boats and cannot sail at all.
|
||||
|
||||
First we have interfaces `RowingBoat` and `FishingBoat`
|
||||
|
||||
```
|
||||
```java
|
||||
public interface RowingBoat {
|
||||
void row();
|
||||
}
|
||||
@ -56,7 +55,7 @@ public class FishingBoat {
|
||||
|
||||
And captain expects an implementation of `RowingBoat` interface to be able to move
|
||||
|
||||
```
|
||||
```java
|
||||
public class Captain implements RowingBoat {
|
||||
|
||||
private RowingBoat rowingBoat;
|
||||
@ -74,7 +73,7 @@ public class Captain implements RowingBoat {
|
||||
|
||||
Now let's say the pirates are coming and our captain needs to escape but there is only fishing boat available. We need to create an adapter that allows the captain to operate the fishing boat with his rowing boat skills.
|
||||
|
||||
```
|
||||
```java
|
||||
public class FishingBoatAdapter implements RowingBoat {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoatAdapter.class);
|
||||
@ -94,7 +93,7 @@ public class FishingBoatAdapter implements RowingBoat {
|
||||
|
||||
And now the `Captain` can use the `FishingBoat` to escape the pirates.
|
||||
|
||||
```
|
||||
```java
|
||||
Captain captain = new Captain(new FishingBoatAdapter());
|
||||
captain.row();
|
||||
```
|
||||
|
@ -29,13 +29,18 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<artifactId>adapter</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -26,7 +26,7 @@ package com.iluwatar.adapter;
|
||||
* The Captain uses {@link RowingBoat} to sail. <br>
|
||||
* This is the client in the pattern.
|
||||
*/
|
||||
public class Captain implements RowingBoat {
|
||||
public class Captain {
|
||||
|
||||
private RowingBoat rowingBoat;
|
||||
|
||||
@ -40,7 +40,6 @@ public class Captain implements RowingBoat {
|
||||
this.rowingBoat = rowingBoat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void row() {
|
||||
rowingBoat.row();
|
||||
}
|
||||
|
@ -22,8 +22,8 @@
|
||||
*/
|
||||
package com.iluwatar.adapter;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
@ -46,7 +46,7 @@ public class AdapterPatternTest {
|
||||
/**
|
||||
* This method runs before the test execution and sets the bean objects in the beans Map.
|
||||
*/
|
||||
@Before
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
beans = new HashMap<>();
|
||||
|
||||
@ -66,7 +66,7 @@ public class AdapterPatternTest {
|
||||
*/
|
||||
@Test
|
||||
public void testAdapter() {
|
||||
RowingBoat captain = (RowingBoat) beans.get(ROWING_BEAN);
|
||||
Captain captain = (Captain) beans.get(ROWING_BEAN);
|
||||
|
||||
// when captain moves
|
||||
captain.row();
|
||||
|
@ -22,7 +22,7 @@
|
||||
*/
|
||||
package com.iluwatar.adapter;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
|
@ -3,7 +3,6 @@ layout: pattern
|
||||
title: Aggregator Microservices
|
||||
folder: aggregator-microservices
|
||||
permalink: /patterns/aggregator-microservices/
|
||||
pumlid: JOov3SCm301NIGQGs7iRXYPa1g8ayB7NjuiKwGvtmBrbKC-Tq_hhY5Y-0HXUjKaS-Kbdepc2HrIQ2jBpma23BvvOTdPfeooCO1iEYlu0O6l63MDQKI6Rp-CKOWSE-ey_NzEqhjH-0m00
|
||||
categories: Architectural
|
||||
tags:
|
||||
- Java
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>aggregator-microservices</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
@ -54,8 +54,13 @@
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -22,15 +22,15 @@
|
||||
*/
|
||||
package com.iluwatar.aggregator.microservices;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test Aggregation of domain objects
|
||||
*/
|
||||
@ -45,7 +45,7 @@ public class AggregatorTest {
|
||||
@Mock
|
||||
private ProductInventoryClient inventoryClient;
|
||||
|
||||
@Before
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
|
@ -1,43 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.aggregator.microservices {
|
||||
class Aggregator {
|
||||
- informationClient : ProductInformationClient
|
||||
- inventoryClient : ProductInventoryClient
|
||||
+ Aggregator()
|
||||
+ getProduct() : Product
|
||||
}
|
||||
class App {
|
||||
+ App()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
class Product {
|
||||
- productInventories : int
|
||||
- title : String
|
||||
+ Product()
|
||||
+ getProductInventories() : int
|
||||
+ getTitle() : String
|
||||
+ setProductInventories(productInventories : int)
|
||||
+ setTitle(title : String)
|
||||
}
|
||||
interface ProductInformationClient {
|
||||
+ getProductTitle() : String {abstract}
|
||||
}
|
||||
class ProductInformationClientImpl {
|
||||
- LOGGER : Logger {static}
|
||||
+ ProductInformationClientImpl()
|
||||
+ getProductTitle() : String
|
||||
}
|
||||
interface ProductInventoryClient {
|
||||
+ getProductInventories() : int {abstract}
|
||||
}
|
||||
class ProductInventoryClientImpl {
|
||||
- LOGGER : Logger {static}
|
||||
+ ProductInventoryClientImpl()
|
||||
+ getProductInventories() : int
|
||||
}
|
||||
}
|
||||
Aggregator --> "-informationClient" ProductInformationClient
|
||||
Aggregator --> "-inventoryClient" ProductInventoryClient
|
||||
ProductInformationClientImpl ..|> ProductInformationClient
|
||||
ProductInventoryClientImpl ..|> ProductInventoryClient
|
||||
@enduml
|
@ -1,12 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.information.microservice {
|
||||
class InformationApplication {
|
||||
+ InformationApplication()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
class InformationController {
|
||||
+ InformationController()
|
||||
+ getProductTitle() : String
|
||||
}
|
||||
}
|
||||
@enduml
|
@ -1,12 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.inventory.microservice {
|
||||
class InventoryApplication {
|
||||
+ InventoryApplication()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
class InventoryController {
|
||||
+ InventoryController()
|
||||
+ getProductInventories() : int
|
||||
}
|
||||
}
|
||||
@enduml
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>aggregator-microservices</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
@ -54,8 +54,13 @@
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
@ -22,8 +22,9 @@
|
||||
*/
|
||||
package com.iluwatar.information.microservice;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Test for Information Rest Controller
|
||||
@ -36,7 +37,7 @@ public class InformationControllerTest {
|
||||
|
||||
String title = infoController.getProductTitle();
|
||||
|
||||
Assert.assertEquals("The Product Title.", title);
|
||||
assertEquals("The Product Title.", title);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>aggregator-microservices</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
@ -54,8 +54,13 @@
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
@ -22,8 +22,9 @@
|
||||
*/
|
||||
package com.iluwatar.inventory.microservice;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Test Inventory Rest Controller
|
||||
@ -35,6 +36,6 @@ public class InventoryControllerTest {
|
||||
|
||||
int numberOfInventories = inventoryController.getProductInventories();
|
||||
|
||||
Assert.assertEquals(5, numberOfInventories);
|
||||
assertEquals(5, numberOfInventories);
|
||||
}
|
||||
}
|
||||
|
@ -29,32 +29,11 @@
|
||||
<parent>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>aggregator-microservices</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>com.github.markusmo3.urm</groupId>
|
||||
<artifactId>urm-maven-plugin</artifactId>
|
||||
<version>${urm.version}</version>
|
||||
<configuration combine.self="override">
|
||||
<outputDirectory>${project.basedir}/../etc</outputDirectory>
|
||||
<packages>
|
||||
<param>com.iluwatar</param>
|
||||
</packages>
|
||||
<skipForProjects>
|
||||
<!-- skip for parent project -->
|
||||
<param>aggregator-microservices</param>
|
||||
</skipForProjects>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<modules>
|
||||
<module>information-microservice</module>
|
||||
<module>aggregator-service</module>
|
||||
|
178
ambassador/README.md
Normal file
178
ambassador/README.md
Normal file
@ -0,0 +1,178 @@
|
||||
---
|
||||
layout: pattern
|
||||
title: Ambassador
|
||||
folder: ambassador
|
||||
permalink: /patterns/ambassador/
|
||||
categories: Structural
|
||||
tags:
|
||||
- Java
|
||||
- Difficulty-Intermediate
|
||||
---
|
||||
|
||||
## Intent
|
||||
Provide a helper service instance on a client and offload common functionality away from a shared resource.
|
||||
|
||||
## Explanation
|
||||
Real world example
|
||||
|
||||
> A remote service has many clients accessing a function it provides. The service is a legacy application and is impossible to update. Large numbers of requests from users are causing connectivity issues. New rules for request frequency should be implemented along with latency checks and client-side logging.
|
||||
|
||||
In plain words
|
||||
|
||||
> Using the ambassador pattern, we can implement less-frequent polling from clients along with latency checks and logging.
|
||||
|
||||
Microsoft documentation states
|
||||
|
||||
> An ambassador service can be thought of as an out-of-process proxy that is co-located with the client.
|
||||
This pattern can be useful for offloading common client connectivity tasks such as monitoring, logging, routing, security (such as TLS), and resiliency patterns in a language agnostic way. It is often used with legacy applications, or other applications that are difficult to modify, in order to extend their networking capabilities. It can also enable a specialized team to implement those features.
|
||||
|
||||
**Programmatic Example**
|
||||
|
||||
With the above example in mind we will imitate the functionality in a simple manner. We have an interface implemented by the remote service as well as the ambassador service:
|
||||
|
||||
```java
|
||||
interface RemoteServiceInterface {
|
||||
|
||||
long doRemoteFunction(int value) throws Exception;
|
||||
}
|
||||
```
|
||||
|
||||
A remote services represented as a singleton.
|
||||
|
||||
```java
|
||||
public class RemoteService implements RemoteServiceInterface {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RemoteService.class);
|
||||
private static RemoteService service = null;2
|
||||
|
||||
static synchronized RemoteService getRemoteService() {
|
||||
if (service == null) {
|
||||
service = new RemoteService();
|
||||
}
|
||||
return service;
|
||||
}
|
||||
|
||||
private RemoteService() {}
|
||||
|
||||
@Override
|
||||
public long doRemoteFunction(int value) {
|
||||
|
||||
long waitTime = (long) Math.floor(Math.random() * 1000);
|
||||
|
||||
try {
|
||||
sleep(waitTime);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.error("Thread sleep interrupted", e)
|
||||
}
|
||||
return waitTime >= 200 ? value * 10 : -1;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A service ambassador adding additional features such as logging, latency checks
|
||||
|
||||
```java
|
||||
public class ServiceAmbassador implements RemoteServiceInterface {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceAmbassador.class);
|
||||
private static final int RETRIES = 3;
|
||||
private static final int DELAY_MS = 3000;
|
||||
|
||||
ServiceAmbassador() {}
|
||||
|
||||
@Override
|
||||
public long doRemoteFunction(int value) {
|
||||
|
||||
return safeCall(value);
|
||||
}
|
||||
|
||||
private long checkLatency(int value) {
|
||||
RemoteService service = RemoteService.getRemoteService();
|
||||
long startTime = System.currentTimeMillis();
|
||||
long result = service.doRemoteFunction(value);
|
||||
long timeTaken = System.currentTimeMillis() - startTime;
|
||||
|
||||
LOGGER.info("Time taken (ms): " + timeTaken);
|
||||
return result;
|
||||
}
|
||||
|
||||
private long safeCall(int value) {
|
||||
|
||||
int retries = 0;
|
||||
long result = -1;
|
||||
|
||||
for (int i = 0; i < RETRIES; i++) {
|
||||
|
||||
if (retries >= RETRIES) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if ((result = checkLatency(value)) == -1) {
|
||||
LOGGER.info("Failed to reach remote: (" + (i + 1) + ")");
|
||||
retries++;
|
||||
try {
|
||||
sleep(DELAY_MS);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.error("Thread sleep state interrupted", e);
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A client has a local service ambassador used to interact with the remote service:
|
||||
|
||||
```java
|
||||
public class Client {
|
||||
|
||||
private ServiceAmbassador serviceAmbassador;
|
||||
|
||||
Client() {
|
||||
serviceAmbassador = new ServiceAmbassador();
|
||||
}
|
||||
|
||||
long useService(int value) {
|
||||
long result = serviceAmbassador.doRemoteFunction(value);
|
||||
LOGGER.info("Service result: " + result)
|
||||
return result;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And here are two clients using the service.
|
||||
|
||||
```java
|
||||
Client host1 = new Client();
|
||||
Client host2 = new Client();
|
||||
host1.useService(12);
|
||||
host2.useService(73);
|
||||
```
|
||||
|
||||
## Applicability
|
||||
Ambassador is applicable when working with a legacy remote service that cannot
|
||||
be modified or would be extremely difficult to modify. Connectivity features can
|
||||
be implemented on the client avoiding the need for changes on the remote service.
|
||||
|
||||
* Ambassador provides a local interface for a remote service.
|
||||
* Ambassador provides logging, circuit breaking, retries and security on the client.
|
||||
|
||||
## Typical Use Case
|
||||
|
||||
* Control access to another object
|
||||
* Implement logging
|
||||
* Implement circuit breaking
|
||||
* Offload remote service tasks
|
||||
* Facilitate network connection
|
||||
|
||||
## Real world examples
|
||||
|
||||
* [Kubernetes-native API gateway for microservices](https://github.com/datawire/ambassador)
|
||||
|
||||
## Credits
|
||||
|
||||
* [Ambassador pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/ambassador)
|
||||
* [Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services](https://books.google.co.uk/books?id=6BJNDwAAQBAJ&pg=PT35&lpg=PT35&dq=ambassador+pattern+in+real+world&source=bl&ots=d2e7GhYdHi&sig=Lfl_MDnCgn6lUcjzOg4GXrN13bQ&hl=en&sa=X&ved=0ahUKEwjk9L_18rrbAhVpKcAKHX_KA7EQ6AEIWTAI#v=onepage&q=ambassador%20pattern%20in%20real%20world&f=false)
|
48
ambassador/pom.xml
Normal file
48
ambassador/pom.xml
Normal file
@ -0,0 +1,48 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
|
||||
The MIT License
|
||||
Copyright (c) 2014-2016 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.
|
||||
|
||||
-->
|
||||
<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">
|
||||
<parent>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>ambassador</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
53
ambassador/src/main/java/com/iluwatar/ambassador/App.java
Normal file
53
ambassador/src/main/java/com/iluwatar/ambassador/App.java
Normal file
@ -0,0 +1,53 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.ambassador;
|
||||
|
||||
/**
|
||||
*
|
||||
* The ambassador pattern creates a helper service that sends network requests on behalf of a
|
||||
* client. It is often used in cloud-based applications to offload features of a remote service.
|
||||
*
|
||||
* An ambassador service can be thought of as an out-of-process proxy that is co-located with
|
||||
* the client. Similar to the proxy design pattern, the ambassador service provides an interface
|
||||
* for another remote service. In addition to the interface, the ambassador provides extra
|
||||
* functionality and features, specifically offloaded common connectivity tasks. This usually
|
||||
* consists of monitoring, logging, routing, security etc. This is extremely useful in
|
||||
* legacy applications where the codebase is difficult to modify and allows for improvements
|
||||
* in the application's networking capabilities.
|
||||
*
|
||||
* In this example, we will the ({@link ServiceAmbassador}) class represents the ambassador while the
|
||||
* ({@link RemoteService}) class represents a remote application.
|
||||
*
|
||||
*/
|
||||
public class App {
|
||||
|
||||
/**
|
||||
* Entry point
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Client host1 = new Client();
|
||||
Client host2 = new Client();
|
||||
host1.useService(12);
|
||||
host2.useService(73);
|
||||
}
|
||||
}
|
42
ambassador/src/main/java/com/iluwatar/ambassador/Client.java
Normal file
42
ambassador/src/main/java/com/iluwatar/ambassador/Client.java
Normal file
@ -0,0 +1,42 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.ambassador;
|
||||
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
|
||||
/**
|
||||
* A simple Client
|
||||
*/
|
||||
public class Client {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);
|
||||
private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador();
|
||||
|
||||
long useService(int value) {
|
||||
long result = serviceAmbassador.doRemoteFunction(value);
|
||||
LOGGER.info("Service result: " + result);
|
||||
return result;
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.ambassador;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import static java.lang.Thread.sleep;
|
||||
|
||||
/**
|
||||
* A remote legacy application represented by a Singleton implementation.
|
||||
*/
|
||||
public class RemoteService implements RemoteServiceInterface {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RemoteService.class);
|
||||
private static RemoteService service = null;
|
||||
|
||||
static synchronized RemoteService getRemoteService() {
|
||||
if (service == null) {
|
||||
service = new RemoteService();
|
||||
}
|
||||
return service;
|
||||
}
|
||||
|
||||
private RemoteService() {}
|
||||
|
||||
/**
|
||||
* Remote function takes a value and multiplies it by 10 taking a random amount of time.
|
||||
* Will sometimes return -1. This imitates connectivity issues a client might have to account for.
|
||||
* @param value integer value to be multiplied.
|
||||
* @return if waitTime is more than 200ms, it returns value * 10, otherwise -1.
|
||||
*/
|
||||
@Override
|
||||
public long doRemoteFunction(int value) {
|
||||
|
||||
long waitTime = (long) Math.floor(Math.random() * 1000);
|
||||
|
||||
try {
|
||||
sleep(waitTime);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.error("Thread sleep state interrupted", e);
|
||||
}
|
||||
return waitTime >= 200 ? value * 10 : -1;
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.ambassador;
|
||||
|
||||
/**
|
||||
* Interface shared by ({@link RemoteService}) and ({@link ServiceAmbassador}).
|
||||
*/
|
||||
interface RemoteServiceInterface {
|
||||
|
||||
long doRemoteFunction(int value) throws Exception;
|
||||
}
|
@ -0,0 +1,84 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.ambassador;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import static java.lang.Thread.sleep;
|
||||
|
||||
/**
|
||||
*
|
||||
* ServiceAmbassador provides an interface for a ({@link Client}) to access ({@link RemoteService}).
|
||||
* The interface adds logging, latency testing and usage of the service in a safe way that will not
|
||||
* add stress to the remote service when connectivity issues occur.
|
||||
*
|
||||
*/
|
||||
public class ServiceAmbassador implements RemoteServiceInterface {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceAmbassador.class);
|
||||
private static final int RETRIES = 3;
|
||||
private static final int DELAY_MS = 3000;
|
||||
|
||||
ServiceAmbassador() {}
|
||||
|
||||
@Override
|
||||
public long doRemoteFunction(int value) {
|
||||
return safeCall(value);
|
||||
}
|
||||
|
||||
private long checkLatency(int value) {
|
||||
long startTime = System.currentTimeMillis();
|
||||
long result = RemoteService.getRemoteService().doRemoteFunction(value);
|
||||
long timeTaken = System.currentTimeMillis() - startTime;
|
||||
|
||||
LOGGER.info("Time taken (ms): " + timeTaken);
|
||||
return result;
|
||||
}
|
||||
|
||||
private long safeCall(int value) {
|
||||
|
||||
int retries = 0;
|
||||
long result = -1;
|
||||
|
||||
for (int i = 0; i < RETRIES; i++) {
|
||||
|
||||
if (retries >= RETRIES) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if ((result = checkLatency(value)) == -1) {
|
||||
LOGGER.info("Failed to reach remote: (" + (i + 1) + ")");
|
||||
retries++;
|
||||
try {
|
||||
sleep(DELAY_MS);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.error("Thread sleep state interrupted", e);
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.ambassador;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Application test
|
||||
*/
|
||||
public class AppTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.ambassador;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Test for {@link Client}
|
||||
*/
|
||||
public class ClientTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
Client client = new Client();
|
||||
long result = client.useService(10);
|
||||
|
||||
assert result == 100 || result == -1;
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.ambassador;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Test for {@link RemoteService}
|
||||
*/
|
||||
public class RemoteServiceTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
long result = RemoteService.getRemoteService().doRemoteFunction(10);
|
||||
assert result == 100 || result == -1;
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 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.ambassador;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Test for {@link ServiceAmbassador}
|
||||
*/
|
||||
public class ServiceAmbassadorTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
long result = new ServiceAmbassador().doRemoteFunction(10);
|
||||
assert result == 100 || result == -1;
|
||||
}
|
||||
}
|
@ -3,7 +3,6 @@ layout: pattern
|
||||
title: API Gateway
|
||||
folder: api-gateway
|
||||
permalink: /patterns/api-gateway/
|
||||
pumlid: JSox3SCm303HLP819FRUXg49cO542_nOyFPncUvUSszHwhbpMdyT4TCt0CDLcyIHdtGsEZLOez8vG7ek33JuueLbPvUcPM84cpeCz2S0fvI6mGjluA1_b-Tt2N5D6tNcw3y0
|
||||
categories: Architectural
|
||||
tags:
|
||||
- Java
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>api-gateway</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>api-gateway-service</artifactId>
|
||||
@ -53,8 +53,13 @@
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -22,15 +22,15 @@
|
||||
*/
|
||||
package com.iluwatar.api.gateway;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test API Gateway Pattern
|
||||
*/
|
||||
@ -45,7 +45,7 @@ public class ApiGatewayTest {
|
||||
@Mock
|
||||
private PriceClient priceClient;
|
||||
|
||||
@Before
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
|
@ -1,48 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.api.gateway {
|
||||
class ApiGateway {
|
||||
- imageClient : ImageClient
|
||||
- priceClient : PriceClient
|
||||
+ ApiGateway()
|
||||
+ getProductDesktop() : DesktopProduct
|
||||
+ getProductMobile() : MobileProduct
|
||||
}
|
||||
class App {
|
||||
+ App()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
class DesktopProduct {
|
||||
- imagePath : String
|
||||
- price : String
|
||||
+ DesktopProduct()
|
||||
+ getImagePath() : String
|
||||
+ getPrice() : String
|
||||
+ setImagePath(imagePath : String)
|
||||
+ setPrice(price : String)
|
||||
}
|
||||
interface ImageClient {
|
||||
+ getImagePath() : String {abstract}
|
||||
}
|
||||
class ImageClientImpl {
|
||||
+ ImageClientImpl()
|
||||
+ getImagePath() : String
|
||||
}
|
||||
class MobileProduct {
|
||||
- price : String
|
||||
+ MobileProduct()
|
||||
+ getPrice() : String
|
||||
+ setPrice(price : String)
|
||||
}
|
||||
interface PriceClient {
|
||||
+ getPrice() : String {abstract}
|
||||
}
|
||||
class PriceClientImpl {
|
||||
+ PriceClientImpl()
|
||||
+ getPrice() : String
|
||||
}
|
||||
}
|
||||
ApiGateway --> "-imageClient" ImageClient
|
||||
ApiGateway --> "-priceClient" PriceClient
|
||||
ImageClientImpl ..|> ImageClient
|
||||
PriceClientImpl ..|> PriceClient
|
||||
@enduml
|
@ -1,12 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.image.microservice {
|
||||
class ImageApplication {
|
||||
+ ImageApplication()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
class ImageController {
|
||||
+ ImageController()
|
||||
+ getImagePath() : String
|
||||
}
|
||||
}
|
||||
@enduml
|
@ -1,12 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.price.microservice {
|
||||
class PriceApplication {
|
||||
+ PriceApplication()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
class PriceController {
|
||||
+ PriceController()
|
||||
+ getPrice() : String
|
||||
}
|
||||
}
|
||||
@enduml
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>api-gateway</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
@ -54,8 +54,13 @@
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
@ -22,8 +22,9 @@
|
||||
*/
|
||||
package com.iluwatar.image.microservice;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Test for Image Rest Controller
|
||||
@ -35,6 +36,6 @@ public class ImageControllerTest {
|
||||
|
||||
String imagePath = imageController.getImagePath();
|
||||
|
||||
Assert.assertEquals("/product-image.png", imagePath);
|
||||
assertEquals("/product-image.png", imagePath);
|
||||
}
|
||||
}
|
||||
|
@ -29,32 +29,11 @@
|
||||
<parent>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>api-gateway</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>com.github.markusmo3.urm</groupId>
|
||||
<artifactId>urm-maven-plugin</artifactId>
|
||||
<version>${urm.version}</version>
|
||||
<configuration combine.self="override">
|
||||
<outputDirectory>${project.basedir}/../etc</outputDirectory>
|
||||
<packages>
|
||||
<param>com.iluwatar</param>
|
||||
</packages>
|
||||
<skipForProjects>
|
||||
<!-- skip for parent project -->
|
||||
<param>api-gateway</param>
|
||||
</skipForProjects>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<modules>
|
||||
<module>image-microservice</module>
|
||||
<module>price-microservice</module>
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>api-gateway</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
@ -54,8 +54,13 @@
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
@ -22,9 +22,9 @@
|
||||
*/
|
||||
package com.iluwatar.price.microservice;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Test for Price Rest Controller
|
||||
@ -36,6 +36,6 @@ public class PriceControllerTest {
|
||||
|
||||
String price = priceController.getPrice();
|
||||
|
||||
Assert.assertEquals("20", price);
|
||||
assertEquals("20", price);
|
||||
}
|
||||
}
|
||||
|
@ -3,7 +3,6 @@ layout: pattern
|
||||
title: Async Method Invocation
|
||||
folder: async-method-invocation
|
||||
permalink: /patterns/async-method-invocation/
|
||||
pumlid: TSdB3SCW303GLTe1mFTkunWhk0A3_4dKxTi5UdlIUuhIoCPfuz4Zjhy03EzwIlGyqjbeQR16fJL1HjuOQF362qjZbrFBnWWsTPZeFm3wHwbCZhvQ4RqMOSXIuA1_LzDctJd75m00
|
||||
categories: Concurrency
|
||||
tags:
|
||||
- Java
|
||||
|
@ -1,51 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.async.method.invocation {
|
||||
class App {
|
||||
- LOGGER : Logger {static}
|
||||
+ App()
|
||||
- callback(name : String) : AsyncCallback<T> {static}
|
||||
- lazyval(value : T, delayMillis : long) : Callable<T> {static}
|
||||
- log(msg : String) {static}
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
interface AsyncCallback<T> {
|
||||
+ onComplete(T, Optional<Exception>) {abstract}
|
||||
}
|
||||
interface AsyncExecutor {
|
||||
+ endProcess(AsyncResult<T>) : T {abstract}
|
||||
+ startProcess(Callable<T>) : AsyncResult<T> {abstract}
|
||||
+ startProcess(Callable<T>, AsyncCallback<T>) : AsyncResult<T> {abstract}
|
||||
}
|
||||
interface AsyncResult<T> {
|
||||
+ await() {abstract}
|
||||
+ getValue() : T {abstract}
|
||||
+ isCompleted() : boolean {abstract}
|
||||
}
|
||||
class ThreadAsyncExecutor {
|
||||
- idx : AtomicInteger
|
||||
+ ThreadAsyncExecutor()
|
||||
+ endProcess(asyncResult : AsyncResult<T>) : T
|
||||
+ startProcess(task : Callable<T>) : AsyncResult<T>
|
||||
+ startProcess(task : Callable<T>, callback : AsyncCallback<T>) : AsyncResult<T>
|
||||
}
|
||||
-class CompletableResult<T> {
|
||||
~ COMPLETED : int {static}
|
||||
~ FAILED : int {static}
|
||||
~ RUNNING : int {static}
|
||||
~ callback : Optional<AsyncCallback<T>>
|
||||
~ exception : Exception
|
||||
~ lock : Object
|
||||
~ state : int
|
||||
~ value : T
|
||||
~ CompletableResult<T>(callback : AsyncCallback<T>)
|
||||
+ await()
|
||||
+ getValue() : T
|
||||
+ isCompleted() : boolean
|
||||
~ setException(exception : Exception)
|
||||
~ setValue(value : T)
|
||||
}
|
||||
}
|
||||
CompletableResult ..+ ThreadAsyncExecutor
|
||||
ThreadAsyncExecutor ..|> AsyncExecutor
|
||||
CompletableResult ..|> AsyncResult
|
||||
@enduml
|
@ -29,13 +29,18 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<artifactId>async-method-invocation</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -22,7 +22,7 @@
|
||||
*/
|
||||
package com.iluwatar.async.method.invocation;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
|
@ -22,7 +22,7 @@
|
||||
*/
|
||||
package com.iluwatar.async.method.invocation;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Matchers;
|
||||
|
||||
@ -30,8 +30,21 @@ import java.util.Optional;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static java.time.Duration.ofMillis;
|
||||
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.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeout;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.internal.verification.VerificationModeFactory.times;
|
||||
|
||||
/**
|
||||
@ -44,205 +57,217 @@ public class ThreadAsyncExecutorTest {
|
||||
/**
|
||||
* Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)}
|
||||
*/
|
||||
@Test(timeout = 3000)
|
||||
@Test
|
||||
public void testSuccessfulTaskWithoutCallback() throws Exception {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
assertTimeout(ofMillis(3000), () -> {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
|
||||
final Object result = new Object();
|
||||
final Callable<Object> task = mock(Callable.class);
|
||||
when(task.call()).thenReturn(result);
|
||||
final Object result = new Object();
|
||||
final Callable<Object> task = mock(Callable.class);
|
||||
when(task.call()).thenReturn(result);
|
||||
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(task);
|
||||
assertNotNull(asyncResult);
|
||||
asyncResult.await(); // Prevent timing issues, and wait until the result is available
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(task);
|
||||
assertNotNull(asyncResult);
|
||||
asyncResult.await(); // Prevent timing issues, and wait until the result is available
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
|
||||
// Our task should only execute once ...
|
||||
verify(task, times(1)).call();
|
||||
// Our task should only execute once ...
|
||||
verify(task, times(1)).call();
|
||||
|
||||
// ... and the result should be exactly the same object
|
||||
assertSame(result, asyncResult.getValue());
|
||||
// ... and the result should be exactly the same object
|
||||
assertSame(result, asyncResult.getValue());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)}
|
||||
*/
|
||||
@Test(timeout = 3000)
|
||||
@Test
|
||||
public void testSuccessfulTaskWithCallback() throws Exception {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
assertTimeout(ofMillis(3000), () -> {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
|
||||
final Object result = new Object();
|
||||
final Callable<Object> task = mock(Callable.class);
|
||||
when(task.call()).thenReturn(result);
|
||||
final Object result = new Object();
|
||||
final Callable<Object> task = mock(Callable.class);
|
||||
when(task.call()).thenReturn(result);
|
||||
|
||||
final AsyncCallback callback = mock(AsyncCallback.class);
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(task, callback);
|
||||
assertNotNull(asyncResult);
|
||||
asyncResult.await(); // Prevent timing issues, and wait until the result is available
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
final AsyncCallback callback = mock(AsyncCallback.class);
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(task, callback);
|
||||
assertNotNull(asyncResult);
|
||||
asyncResult.await(); // Prevent timing issues, and wait until the result is available
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
|
||||
// Our task should only execute once ...
|
||||
verify(task, times(1)).call();
|
||||
// Our task should only execute once ...
|
||||
verify(task, times(1)).call();
|
||||
|
||||
// ... same for the callback, we expect our object
|
||||
final ArgumentCaptor<Optional<Exception>> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class);
|
||||
verify(callback, times(1)).onComplete(eq(result), optionalCaptor.capture());
|
||||
// ... same for the callback, we expect our object
|
||||
final ArgumentCaptor<Optional<Exception>> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class);
|
||||
verify(callback, times(1)).onComplete(eq(result), optionalCaptor.capture());
|
||||
|
||||
final Optional<Exception> optionalException = optionalCaptor.getValue();
|
||||
assertNotNull(optionalException);
|
||||
assertFalse(optionalException.isPresent());
|
||||
final Optional<Exception> optionalException = optionalCaptor.getValue();
|
||||
assertNotNull(optionalException);
|
||||
assertFalse(optionalException.isPresent());
|
||||
|
||||
// ... and the result should be exactly the same object
|
||||
assertSame(result, asyncResult.getValue());
|
||||
// ... and the result should be exactly the same object
|
||||
assertSame(result, asyncResult.getValue());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while
|
||||
* to execute
|
||||
*/
|
||||
@Test(timeout = 5000)
|
||||
@Test
|
||||
public void testLongRunningTaskWithoutCallback() throws Exception {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
assertTimeout(ofMillis(5000), () -> {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
|
||||
final Object result = new Object();
|
||||
final Callable<Object> task = mock(Callable.class);
|
||||
when(task.call()).thenAnswer(i -> {
|
||||
Thread.sleep(1500);
|
||||
return result;
|
||||
final Object result = new Object();
|
||||
final Callable<Object> task = mock(Callable.class);
|
||||
when(task.call()).thenAnswer(i -> {
|
||||
Thread.sleep(1500);
|
||||
return result;
|
||||
});
|
||||
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(task);
|
||||
assertNotNull(asyncResult);
|
||||
assertFalse(asyncResult.isCompleted());
|
||||
|
||||
try {
|
||||
asyncResult.getValue();
|
||||
fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task");
|
||||
} catch (IllegalStateException e) {
|
||||
assertNotNull(e.getMessage());
|
||||
}
|
||||
|
||||
// Our task should only execute once, but it can take a while ...
|
||||
verify(task, timeout(3000).times(1)).call();
|
||||
|
||||
// Prevent timing issues, and wait until the result is available
|
||||
asyncResult.await();
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
verifyNoMoreInteractions(task);
|
||||
|
||||
// ... and the result should be exactly the same object
|
||||
assertSame(result, asyncResult.getValue());
|
||||
});
|
||||
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(task);
|
||||
assertNotNull(asyncResult);
|
||||
assertFalse(asyncResult.isCompleted());
|
||||
|
||||
try {
|
||||
asyncResult.getValue();
|
||||
fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task");
|
||||
} catch (IllegalStateException e) {
|
||||
assertNotNull(e.getMessage());
|
||||
}
|
||||
|
||||
// Our task should only execute once, but it can take a while ...
|
||||
verify(task, timeout(3000).times(1)).call();
|
||||
|
||||
// Prevent timing issues, and wait until the result is available
|
||||
asyncResult.await();
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
verifyNoMoreInteractions(task);
|
||||
|
||||
// ... and the result should be exactly the same object
|
||||
assertSame(result, asyncResult.getValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when a task
|
||||
* takes a while to execute
|
||||
*/
|
||||
@Test(timeout = 5000)
|
||||
@Test
|
||||
public void testLongRunningTaskWithCallback() throws Exception {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
assertTimeout(ofMillis(5000), () -> {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
|
||||
final Object result = new Object();
|
||||
final Callable<Object> task = mock(Callable.class);
|
||||
when(task.call()).thenAnswer(i -> {
|
||||
Thread.sleep(1500);
|
||||
return result;
|
||||
final Object result = new Object();
|
||||
final Callable<Object> task = mock(Callable.class);
|
||||
when(task.call()).thenAnswer(i -> {
|
||||
Thread.sleep(1500);
|
||||
return result;
|
||||
});
|
||||
|
||||
final AsyncCallback<Object> callback = mock(AsyncCallback.class);
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(task, callback);
|
||||
assertNotNull(asyncResult);
|
||||
assertFalse(asyncResult.isCompleted());
|
||||
|
||||
verifyZeroInteractions(callback);
|
||||
|
||||
try {
|
||||
asyncResult.getValue();
|
||||
fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task");
|
||||
} catch (IllegalStateException e) {
|
||||
assertNotNull(e.getMessage());
|
||||
}
|
||||
|
||||
// Our task should only execute once, but it can take a while ...
|
||||
verify(task, timeout(3000).times(1)).call();
|
||||
|
||||
final ArgumentCaptor<Optional<Exception>> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class);
|
||||
verify(callback, timeout(3000).times(1)).onComplete(eq(result), optionalCaptor.capture());
|
||||
|
||||
final Optional<Exception> optionalException = optionalCaptor.getValue();
|
||||
assertNotNull(optionalException);
|
||||
assertFalse(optionalException.isPresent());
|
||||
|
||||
// Prevent timing issues, and wait until the result is available
|
||||
asyncResult.await();
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
verifyNoMoreInteractions(task, callback);
|
||||
|
||||
// ... and the result should be exactly the same object
|
||||
assertSame(result, asyncResult.getValue());
|
||||
});
|
||||
|
||||
final AsyncCallback<Object> callback = mock(AsyncCallback.class);
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(task, callback);
|
||||
assertNotNull(asyncResult);
|
||||
assertFalse(asyncResult.isCompleted());
|
||||
|
||||
verifyZeroInteractions(callback);
|
||||
|
||||
try {
|
||||
asyncResult.getValue();
|
||||
fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task");
|
||||
} catch (IllegalStateException e) {
|
||||
assertNotNull(e.getMessage());
|
||||
}
|
||||
|
||||
// Our task should only execute once, but it can take a while ...
|
||||
verify(task, timeout(3000).times(1)).call();
|
||||
|
||||
final ArgumentCaptor<Optional<Exception>> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class);
|
||||
verify(callback, timeout(3000).times(1)).onComplete(eq(result), optionalCaptor.capture());
|
||||
|
||||
final Optional<Exception> optionalException = optionalCaptor.getValue();
|
||||
assertNotNull(optionalException);
|
||||
assertFalse(optionalException.isPresent());
|
||||
|
||||
// Prevent timing issues, and wait until the result is available
|
||||
asyncResult.await();
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
verifyNoMoreInteractions(task, callback);
|
||||
|
||||
// ... and the result should be exactly the same object
|
||||
assertSame(result, asyncResult.getValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while
|
||||
* to execute, while waiting on the result using {@link ThreadAsyncExecutor#endProcess(AsyncResult)}
|
||||
*/
|
||||
@Test(timeout = 5000)
|
||||
@Test
|
||||
public void testEndProcess() throws Exception {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
assertTimeout(ofMillis(5000), () -> {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
|
||||
final Object result = new Object();
|
||||
final Callable<Object> task = mock(Callable.class);
|
||||
when(task.call()).thenAnswer(i -> {
|
||||
Thread.sleep(1500);
|
||||
return result;
|
||||
final Object result = new Object();
|
||||
final Callable<Object> task = mock(Callable.class);
|
||||
when(task.call()).thenAnswer(i -> {
|
||||
Thread.sleep(1500);
|
||||
return result;
|
||||
});
|
||||
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(task);
|
||||
assertNotNull(asyncResult);
|
||||
assertFalse(asyncResult.isCompleted());
|
||||
|
||||
try {
|
||||
asyncResult.getValue();
|
||||
fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task");
|
||||
} catch (IllegalStateException e) {
|
||||
assertNotNull(e.getMessage());
|
||||
}
|
||||
|
||||
assertSame(result, executor.endProcess(asyncResult));
|
||||
verify(task, times(1)).call();
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
|
||||
// Calling end process a second time while already finished should give the same result
|
||||
assertSame(result, executor.endProcess(asyncResult));
|
||||
verifyNoMoreInteractions(task);
|
||||
});
|
||||
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(task);
|
||||
assertNotNull(asyncResult);
|
||||
assertFalse(asyncResult.isCompleted());
|
||||
|
||||
try {
|
||||
asyncResult.getValue();
|
||||
fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task");
|
||||
} catch (IllegalStateException e) {
|
||||
assertNotNull(e.getMessage());
|
||||
}
|
||||
|
||||
assertSame(result, executor.endProcess(asyncResult));
|
||||
verify(task, times(1)).call();
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
|
||||
// Calling end process a second time while already finished should give the same result
|
||||
assertSame(result, executor.endProcess(asyncResult));
|
||||
verifyNoMoreInteractions(task);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable)} when the callable is 'null'
|
||||
*/
|
||||
@Test(timeout = 3000)
|
||||
@Test
|
||||
public void testNullTask() throws Exception {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(null);
|
||||
assertTimeout(ofMillis(3000), () -> {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(null);
|
||||
|
||||
assertNotNull("The AsyncResult should not be 'null', even though the task was 'null'.", asyncResult);
|
||||
asyncResult.await(); // Prevent timing issues, and wait until the result is available
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
assertNotNull(asyncResult, "The AsyncResult should not be 'null', even though the task was 'null'.");
|
||||
asyncResult.await(); // Prevent timing issues, and wait until the result is available
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
|
||||
try {
|
||||
asyncResult.getValue();
|
||||
fail("Expected ExecutionException with NPE as cause");
|
||||
} catch (final ExecutionException e) {
|
||||
assertNotNull(e.getMessage());
|
||||
assertNotNull(e.getCause());
|
||||
assertEquals(NullPointerException.class, e.getCause().getClass());
|
||||
}
|
||||
try {
|
||||
asyncResult.getValue();
|
||||
fail("Expected ExecutionException with NPE as cause");
|
||||
} catch (final ExecutionException e) {
|
||||
assertNotNull(e.getMessage());
|
||||
assertNotNull(e.getCause());
|
||||
assertEquals(NullPointerException.class, e.getCause().getClass());
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@ -250,36 +275,38 @@ public class ThreadAsyncExecutorTest {
|
||||
* Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when the
|
||||
* callable is 'null', but the asynchronous callback is provided
|
||||
*/
|
||||
@Test(timeout = 3000)
|
||||
@Test
|
||||
public void testNullTaskWithCallback() throws Exception {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
final AsyncCallback<Object> callback = mock(AsyncCallback.class);
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(null, callback);
|
||||
assertTimeout(ofMillis(3000), () -> {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
final AsyncCallback<Object> callback = mock(AsyncCallback.class);
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(null, callback);
|
||||
|
||||
assertNotNull("The AsyncResult should not be 'null', even though the task was 'null'.", asyncResult);
|
||||
asyncResult.await(); // Prevent timing issues, and wait until the result is available
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
assertNotNull(asyncResult, "The AsyncResult should not be 'null', even though the task was 'null'.");
|
||||
asyncResult.await(); // Prevent timing issues, and wait until the result is available
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
|
||||
final ArgumentCaptor<Optional<Exception>> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class);
|
||||
verify(callback, times(1)).onComplete(Matchers.isNull(), optionalCaptor.capture());
|
||||
final ArgumentCaptor<Optional<Exception>> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class);
|
||||
verify(callback, times(1)).onComplete(Matchers.isNull(), optionalCaptor.capture());
|
||||
|
||||
final Optional<Exception> optionalException = optionalCaptor.getValue();
|
||||
assertNotNull(optionalException);
|
||||
assertTrue(optionalException.isPresent());
|
||||
final Optional<Exception> optionalException = optionalCaptor.getValue();
|
||||
assertNotNull(optionalException);
|
||||
assertTrue(optionalException.isPresent());
|
||||
|
||||
final Exception exception = optionalException.get();
|
||||
assertNotNull(exception);
|
||||
assertEquals(NullPointerException.class, exception.getClass());
|
||||
final Exception exception = optionalException.get();
|
||||
assertNotNull(exception);
|
||||
assertEquals(NullPointerException.class, exception.getClass());
|
||||
|
||||
try {
|
||||
asyncResult.getValue();
|
||||
fail("Expected ExecutionException with NPE as cause");
|
||||
} catch (final ExecutionException e) {
|
||||
assertNotNull(e.getMessage());
|
||||
assertNotNull(e.getCause());
|
||||
assertEquals(NullPointerException.class, e.getCause().getClass());
|
||||
}
|
||||
try {
|
||||
asyncResult.getValue();
|
||||
fail("Expected ExecutionException with NPE as cause");
|
||||
} catch (final ExecutionException e) {
|
||||
assertNotNull(e.getMessage());
|
||||
assertNotNull(e.getCause());
|
||||
assertEquals(NullPointerException.class, e.getCause().getClass());
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@ -287,24 +314,29 @@ public class ThreadAsyncExecutorTest {
|
||||
* Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when both
|
||||
* the callable and the asynchronous callback are 'null'
|
||||
*/
|
||||
@Test(timeout = 3000)
|
||||
@Test
|
||||
public void testNullTaskWithNullCallback() throws Exception {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(null, null);
|
||||
assertTimeout(ofMillis(3000), () -> {
|
||||
// Instantiate a new executor and start a new 'null' task ...
|
||||
final ThreadAsyncExecutor executor = new ThreadAsyncExecutor();
|
||||
final AsyncResult<Object> asyncResult = executor.startProcess(null, null);
|
||||
|
||||
assertNotNull("The AsyncResult should not be 'null', even though the task and callback were 'null'.", asyncResult);
|
||||
asyncResult.await(); // Prevent timing issues, and wait until the result is available
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
assertNotNull(
|
||||
asyncResult,
|
||||
"The AsyncResult should not be 'null', even though the task and callback were 'null'."
|
||||
);
|
||||
asyncResult.await(); // Prevent timing issues, and wait until the result is available
|
||||
assertTrue(asyncResult.isCompleted());
|
||||
|
||||
try {
|
||||
asyncResult.getValue();
|
||||
fail("Expected ExecutionException with NPE as cause");
|
||||
} catch (final ExecutionException e) {
|
||||
assertNotNull(e.getMessage());
|
||||
assertNotNull(e.getCause());
|
||||
assertEquals(NullPointerException.class, e.getCause().getClass());
|
||||
}
|
||||
try {
|
||||
asyncResult.getValue();
|
||||
fail("Expected ExecutionException with NPE as cause");
|
||||
} catch (final ExecutionException e) {
|
||||
assertNotNull(e.getMessage());
|
||||
assertNotNull(e.getCause());
|
||||
assertEquals(NullPointerException.class, e.getCause().getClass());
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
@ -18,10 +18,10 @@ incomplete or inappropriate state
|
||||
## Applicability
|
||||
Use the Balking pattern when
|
||||
|
||||
*you want to invoke an action on an object only when it is in a particular state
|
||||
*objects are generally only in a state that is prone to balking temporarily
|
||||
* you want to invoke an action on an object only when it is in a particular state
|
||||
* objects are generally only in a state that is prone to balking temporarily
|
||||
but for an unknown amount of time
|
||||
|
||||
## Related patterns
|
||||
* Guarded Suspension Pattern
|
||||
* Double Checked Locking Pattern
|
||||
* Double Checked Locking Pattern
|
||||
|
@ -1,24 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.balking {
|
||||
class App {
|
||||
- LOGGER : Logger {static}
|
||||
+ App()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
class WashingMachine {
|
||||
- LOGGER : Logger {static}
|
||||
- washingMachineState : WashingMachineState
|
||||
+ WashingMachine()
|
||||
+ endOfWashing()
|
||||
+ getWashingMachineState() : WashingMachineState
|
||||
+ wash()
|
||||
}
|
||||
enum WashingMachineState {
|
||||
+ ENABLED {static}
|
||||
+ WASHING {static}
|
||||
+ valueOf(name : String) : WashingMachineState {static}
|
||||
+ values() : WashingMachineState[] {static}
|
||||
}
|
||||
}
|
||||
WashingMachine --> "-washingMachineState" WashingMachineState
|
||||
@enduml
|
@ -29,15 +29,20 @@
|
||||
<parent>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>balking</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
@ -23,7 +23,7 @@
|
||||
|
||||
package com.iluwatar.balking;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Application test
|
||||
|
@ -22,13 +22,14 @@
|
||||
*/
|
||||
package com.iluwatar.balking;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Tests for {@link WashingMachine}
|
||||
@ -37,6 +38,7 @@ public class WashingMachineTest {
|
||||
|
||||
private volatile WashingMachineState machineStateGlobal;
|
||||
|
||||
@Disabled
|
||||
@Test
|
||||
public void wash() throws Exception {
|
||||
WashingMachine washingMachine = new WashingMachine();
|
||||
|
@ -3,7 +3,6 @@ layout: pattern
|
||||
title: Bridge
|
||||
folder: bridge
|
||||
permalink: /patterns/bridge/
|
||||
pumlid: BSR14SCm20J0Lf82BFxf1akCJ4R26ZZYzkE7zxLljJgoIVfu7S2A3v7pLRhYo3r3l9u6CPHwJjAH5uETllpZhKbejsqn86v1a-CExQwj2mdgqv8-oyev_W00
|
||||
categories: Structural
|
||||
tags:
|
||||
- Java
|
||||
@ -35,7 +34,7 @@ Wikipedia says
|
||||
|
||||
Translating our weapon example from above. Here we have the `Weapon` hierarchy
|
||||
|
||||
```
|
||||
```java
|
||||
public interface Weapon {
|
||||
void wield();
|
||||
void swing();
|
||||
@ -110,7 +109,7 @@ public class Hammer implements Weapon {
|
||||
|
||||
And the separate enchantment hierarchy
|
||||
|
||||
```
|
||||
```java
|
||||
public interface Enchantment {
|
||||
void onActivate();
|
||||
void apply();
|
||||
@ -156,7 +155,7 @@ public class SoulEatingEnchantment implements Enchantment {
|
||||
|
||||
And both the hierarchies in action
|
||||
|
||||
```
|
||||
```java
|
||||
Sword enchantedSword = new Sword(new SoulEatingEnchantment());
|
||||
enchantedSword.wield();
|
||||
enchantedSword.swing();
|
||||
@ -189,6 +188,9 @@ Use the Bridge pattern when
|
||||
* you have a proliferation of classes. Such a class hierarchy indicates the need for splitting an object into two parts. Rumbaugh uses the term "nested generalizations" to refer to such class hierarchies
|
||||
* you want to share an implementation among multiple objects (perhaps using reference counting), and this fact should be hidden from the client. A simple example is Coplien's String class, in which multiple objects can share the same string representation.
|
||||
|
||||
## Tutorial
|
||||
* [Bridge Pattern Tutorial](https://www.journaldev.com/1491/bridge-design-pattern-java)
|
||||
|
||||
## Credits
|
||||
|
||||
* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612)
|
||||
|
@ -29,13 +29,18 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<artifactId>bridge</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -22,7 +22,7 @@
|
||||
*/
|
||||
package com.iluwatar.bridge;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
|
@ -22,11 +22,10 @@
|
||||
*/
|
||||
package com.iluwatar.bridge;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* Tests for hammer
|
||||
|
@ -22,11 +22,10 @@
|
||||
*/
|
||||
package com.iluwatar.bridge;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* Tests for sword
|
||||
|
@ -22,10 +22,11 @@
|
||||
*/
|
||||
package com.iluwatar.bridge;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.internal.verification.VerificationModeFactory.times;
|
||||
|
||||
/**
|
||||
* Base class for weapon tests
|
||||
|
@ -3,7 +3,6 @@ layout: pattern
|
||||
title: Builder
|
||||
folder: builder
|
||||
permalink: /patterns/builder/
|
||||
pumlid: DSR94O0m2030LhG0mzzkC64KXs26GzlNZw_TcRLADagJwOWOlW8OFcNdE79B9wkN1ccKUdLWoGS33KwySMdalEioC89C7Jhw5zYIfNrIrFybhPUHNLu0
|
||||
categories: Creational
|
||||
tags:
|
||||
- Java
|
||||
@ -32,7 +31,7 @@ Wikipedia says
|
||||
|
||||
Having said that let me add a bit about what telescoping constructor anti-pattern is. At one point or the other we have all seen a constructor like below:
|
||||
|
||||
```
|
||||
```java
|
||||
public Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon) {
|
||||
}
|
||||
```
|
||||
@ -43,7 +42,7 @@ As you can see the number of constructor parameters can quickly get out of hand
|
||||
|
||||
The sane alternative is to use the Builder pattern. First of all we have our hero that we want to create
|
||||
|
||||
```
|
||||
```java
|
||||
public final class Hero {
|
||||
private final Profession profession;
|
||||
private final String name;
|
||||
@ -65,7 +64,7 @@ public final class Hero {
|
||||
|
||||
And then we have the builder
|
||||
|
||||
```
|
||||
```java
|
||||
public static class Builder {
|
||||
private final Profession profession;
|
||||
private final String name;
|
||||
@ -110,7 +109,7 @@ And then we have the builder
|
||||
|
||||
And then it can be used as:
|
||||
|
||||
```
|
||||
```java
|
||||
Hero mage = new Hero.Builder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER).build();
|
||||
```
|
||||
|
||||
|
@ -29,13 +29,18 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.20.0</version>
|
||||
</parent>
|
||||
<artifactId>builder</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
@ -22,7 +22,7 @@
|
||||
*/
|
||||
package com.iluwatar.builder;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
|
@ -22,10 +22,11 @@
|
||||
*/
|
||||
package com.iluwatar.builder;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* Date: 12/6/15 - 11:01 PM
|
||||
@ -37,17 +38,17 @@ public class HeroTest {
|
||||
/**
|
||||
* Test if we get the expected exception when trying to create a hero without a profession
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
@Test
|
||||
public void testMissingProfession() throws Exception {
|
||||
new Hero.Builder(null, "Sir without a job");
|
||||
assertThrows(IllegalArgumentException.class, () -> new Hero.Builder(null, "Sir without a job"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if we get the expected exception when trying to create a hero without a name
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
@Test
|
||||
public void testMissingName() throws Exception {
|
||||
new Hero.Builder(Profession.THIEF, null);
|
||||
assertThrows(IllegalArgumentException.class, () -> new Hero.Builder(Profession.THIEF, null));
|
||||
}
|
||||
|
||||
/**
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user