Compare commits

..

351 Commits

Author SHA1 Message Date
9bf7a059b8 Java Design Patterns v1.21.0 2019-09-08 10:49:40 +03:00
88fae070e6 Fix broken links #915 (#921) 2019-09-07 21:18:13 +03:00
f1410337b5 Fix issue #761: ThreadSafeDoubleCheckLocking.java: Instantiating by Reflection call will be successful if you do that firstly (#920) 2019-09-07 21:13:15 +03:00
8c865e6b4d clean code (#910) 2019-09-07 21:07:01 +03:00
c653edf38f fix must override a superclass method (#919)
* fix must override a superclass method

* fix must override a superclass method
2019-09-07 20:52:49 +03:00
35dc25d480 MInor bug fix Issue #895 -> Code comment change (https://github.com/iluwatar/java-design-patterns/issues/895) (#901) 2019-09-07 20:24:40 +03:00
318f811fea Bytecode pattern #553 (#896)
* Added bytecode pattern

* Diagram changed and added licence information

* Added bytecode module to main pom.

* Fixed missing dependency error
2019-09-03 21:50:48 +03:00
7f6067f19f Added priority queue design pattern (#888)
* added priority queue design pattern

* Minor Refactored, fixed review comments
2019-08-31 21:10:35 +03:00
11c0550559 Create .sonarcloud.properties 2019-08-21 21:51:27 +03:00
085e47b50d Update SonarCloud badge 2019-08-21 21:47:36 +03:00
61ef59de02 fix code example containing syntax error (#890) 2019-08-11 21:06:27 +03:00
ccb257d525 fixed bug #883 (#885) 2019-08-04 17:11:56 +03:00
6daaeec5c6 Remove the transitive dependency(junit-jupiter-api) (#916) 2019-07-30 22:46:38 +03:00
517c20960d Added one more Credit/Article about the benefits of Repository pattern (#882) 2019-07-29 21:31:42 +03:00
36e80c4e69 fixed failing tests (#860) (#880) 2019-07-29 21:27:08 +03:00
3454941dcd Typo coresponding -> corresponding (#879) 2019-07-29 21:22:56 +03:00
b497d41f61 Modify Observer pattern UML (#877) 2019-07-29 21:21:07 +03:00
aaabc8f517 Fix the dependency conflict issue (#872) 2019-07-29 21:16:21 +03:00
2757b210ea Best practice when compare enum (#869) 2019-07-29 21:12:14 +03:00
d9a567cf97 Commander pattern #505 (#857)
* Commander pattern

* Fix checkstyle errors

* Update Commander.java

* Update README.md

* Update PaymentService.java

* Update Commander.java

* Update README.md
2019-07-29 21:09:08 +03:00
a113de6a14 Add licenses 2019-07-28 16:24:14 +03:00
f7e22a1cf6 508 : Sonar qube critical Issue Fix (#854)
* 508 : Sonar qube critical Issue Fix
Refactor this method to reduce its Cognitive Complexity from 30 to the 15 allowed.

* 508: Sonar Qube Issue fxes
Define a constant instead of duplicating this literal " does not exist." 3 times.

* 508: sonar qube issue fixes
Define a constant instead of duplicating this literal "Some external api for only realtime execution could be called here." 3 times.
2019-07-28 15:42:03 +03:00
c6ecf58687 508 : sonar qube critical issue fixes (#852)
* 508 : sonar qube critical issue fixes

* 508 : Sunar Qube Fixes
Define a constant instead of duplicating this literal "user_accounts" 4 times.
Define a constant instead of duplicating this literal "userID" 5 times
Define a constant instead of duplicating this literal "additionalInfo" 4 times.
Define a constant instead of duplicating this literal "userName" 4 times.

* 508 : Sunar Qube Fixes
Define a constant instead of duplicating this literal "user_accounts" 4 times.

* 508 : Sonar Qube Fixes
Define a constant instead of duplicating this literal "eEvans" 4 times
Define a constant instead of duplicating this literal "jBloch" 6 times
Define a constant instead of duplicating this literal "mFowler" 3 times

* 508 : Sonar Qube FIxes
Define a constant instead of duplicating this literal "username" 3 times.

* 508: sonar qube issue fixes
Define a constant instead of duplicating this literal "customerDao.getAllCustomers(): " 4 times.

* 508 : sonar qube issue fixes
Define a constant instead of duplicating this literal "App.main(), student : " 4 times.

* 508 : sonar Qube issue fixes
Define a constant instead of duplicating this literal "{} hits {}. {} is damaged!" 3 times.
Define a constant instead of duplicating this literal "{} hits {}." 4 times.

* 508 : Define a constant instead of duplicating this literal "{} hits {}." 4 times.

* 508 : checkstyle fixes

* 508: checkstyle fixes

* 508: checkstyle fixes

* 508: checkstyle fixes

* 508: checkstyle fixes

* 508: checkstyle fixes

* 508: cqrs checkstyle fixes
2019-07-28 15:39:40 +03:00
17bfc91f45 Change Travis CI build env. to Trusty (#911) 2019-07-28 14:20:18 +03:00
0c6237c225 Type object pattern #555 (#848)
* typeobject pattern

* fixing errors

* fix error cellpool

* Update README.md

* Update README.md
2019-07-24 22:08:30 +03:00
fedc2d9e47 Minor ReadMe Update (#864)
Two sentences read a little awkward, so I tweaked them. Hope this helps!
2019-04-07 08:41:35 +03:00
b6b4602baf 845 : unnecassary return deleted (#856) 2019-02-16 22:53:06 +02:00
eafe52e17a 756 : faq added (#855) 2019-02-15 20:00:21 +02:00
5251ec4a93 removed unnecessary static modifier on enum definition (#853) 2019-02-15 19:55:23 +02:00
26f1a608ab Update license headers 2019-02-13 23:14:53 +02:00
7a25c57474 Master worker pattern #799 (#831)
* master worker pattern

* Update App.java

* Adding new line to README.md

* Adding new line to pom.xml

* Adding new line to ArrayEquality.java

* Adding new line to Input.java

* Adding new line to Result.java

* Adding new line to ArrayTransposeMasterWorker.java

* Adding new line to ArrayTransposeMaster.java

* Adding new line to ArrayTransposeWorker.java

* Adding new line to Worker.java

* Adding new line to ArrayInputTest.java

* Adding new line ArrayTransposeMasterWorkerTest.java

* Adding new line to ArrayResult.java

* Review changes

* Update README.md
2019-02-13 23:04:16 +02:00
55c7579983 Fix script blocking (#843) 2019-02-04 08:35:06 +02:00
10cb191533 Retry exponential backoff #775 (#829)
* Spatial partition

* Retry with exponential backoff

* retry exponential backoff

* branch error
2019-02-04 08:27:13 +02:00
a6749cb63e Spatial partition pattern #562 (#828)
* Spatial partition

* Update pom.xml

* Update Bubble.java - pmd

* Update Rect.java - pmd
2018-12-22 23:37:31 +02:00
7b8c9b07ed Fix typo (#832) 2018-12-17 12:12:54 +05:30
0fa18d91c6 Added real world example of Command pattern
JUnit 4 Statement class is also an example of Command pattern. Added that to list of real world examples
2018-12-03 18:58:20 +05:30
53b673d5b0 No Need declare App class as a utility class (#827) 2018-11-25 19:35:22 +02:00
966c56311c Update Readme.md (#815)
Added a tutorial link for  intercepting filter design pattern
2018-11-04 20:12:04 +02:00
150f72758e Add missing license headers 2018-11-03 09:13:59 +02:00
4446e74338 Hexagonal pattern fixes (#814)
* Fixed wrong else condition

* Simplified creating Set of numbers

* Deleted unused imports

* Replaced 'for' loop with 'foreach' one

* Replaced explicit type with diamond

* Removed unnecesary brackets from lambda

* Removed unnecesary contains check before adding element to Set

* Fixed typo and changed non-english constant names
2018-10-27 16:39:16 +05:30
70f6e54353 Fix blocker issues on Sonar #508 (#810)
* Fix blocker issues on Sonar

* Replace Assertj assertions with JUnit ones
2018-10-25 18:43:58 +05:30
1f1fcae513 Refactor Page-object pattern (#812)
* Refactor : create 2 sub-modules for page-object pattern

* Replace e.printStrackTrace with logger
2018-10-24 23:17:46 +03:00
2aa9e78ddd Minor refactorings and code style changes (#807)
* Made minor changes in some patterns such as removed throws clause where not needed, changed incorrect order of arguments in assertEquals

* Minor refactorings and code style changes. 1) Removed several use of raw types 2) Removed unnecessary throws clauses 3) Used lambda expressions wherever applicable 4) Used apt assertion methods for readability 5) Use of try with resources wherever applicable 6) Corrected incorrect order of assertXXX arguments

* Removed unused import from Promise

* Addressed review comments

* Addressed checkstyle issue
2018-10-23 13:45:41 +05:30
25ed7c09c5 Refactored Event Queue (#806)
* 1) Test cases were not stopping AudioService before ending test case 2) Changed Audio to be a good singleton, previously because of Audio being bad singleton, test cases which were using static methods could have caused intermittent failures. 3) Made some other refactorings as well

* Removed sonar issue and converted Audio to eager singleton for simplicity

* Updated class diagram PNG
2018-10-21 21:15:33 +03:00
922fd62da6 Resolves #643, test cases failed due to global state in CallsCount (#803)
* Resolves #643, test cases failed due to presence of global state in CallsCount. Because AppTest was executed before B2BServiceTest, it scheduled 1 sec timer using ThrottleTimerImpl class. While resetting it used that global CallCount class reset() method, which reset all counters. So that causes thread safety issue because of unintended sharing of application state between test cases, which is not a good practice.

* Updated class diagram png and added UCLS file
2018-10-21 21:14:07 +03:00
9e7a500743 Refactoring changes in Ambassador Pattern (#805)
* 1) Updated test cases to use Junit Assert method as compared to assert keyword 2) Proper testing of RemoteService using RandomProvider interface. Introduced RandomProvider interface so that randomness can be controlled from test cases. 3) For readability used constant for representing FAILURE

* Addressing review comments, Deleting unintentional file and used FAILURE constant in ClientTest as well
2018-10-21 21:12:03 +03:00
21a149ee77 Merge pull request #801 from iluwatar/HexagonalRefactoring
Minor refactorings in Hexagonal architecture
2018-10-21 09:54:28 +03:00
f5eaf06c1c Merge pull request #802 from iluwatar/Issue#699
Resolves #699 Intermittent failure was due to Thread.sleep in the code
2018-10-21 09:25:06 +03:00
3c6fb0c53b Merge pull request #800 from trumvekhuya/master
Fix small points in Strategy and Decorator pattern.
2018-10-21 08:46:24 +03:00
829df031c3 Intermittent failure was due to Thread.sleep in the code. While performing unit test cases there was race condition between two threads, so it was not guaranteed to work every time. Used an interface DelayProvider for simulating delay, and while unit testing fake delay provider is used that eradicates the use of Threads in unit test cases, which is not a good practice. 2018-10-15 16:36:27 +05:30
37ae182630 Resolved PMD issues 2018-10-15 13:30:20 +05:30
ab2c12e734 1) Refactored LotteryNumbers to use Joiner from guava library to join lottery numbers. 2) Solved potential thread safety issue in LotteryTicketId class, where it was using raw primitive value and incrementing it which is not thread-safe. So used AtomicInteger for brevity 3) assertEquals arguments were in incorrect order at many places, so changed order of those 4) Replaced assertFalse and assertTrue at some places with assertEquals and assertNotEquals for reducing complexity of code 5) Removed public modifiers from test cases, as they are no more needed by JUnit 5 2018-10-15 13:21:00 +05:30
b3f0cc7e00 - Assign ClubberTroll to another variable in README 2018-10-15 11:52:56 +07:00
86e9c66ca5 - Assign new clubberTroll instance to another variable.
- Remove redundant Exception from throws list in unit tests.
2018-10-15 11:41:14 +07:00
a6e6c22bf6 Remove redundant Exception from throws list in DragonSlayerTest 2018-10-15 10:44:14 +07:00
db33cc533b Remove CII best practices badge 2018-10-13 18:40:10 +03:00
8433c7b712 Merge pull request #793 from andrievsky/master
Fix redundant list alloc in LotteryNumbers
2018-10-13 18:28:40 +03:00
ee74fec53c Fix pattern title 2018-09-30 21:36:32 +03:00
7a7e891384 Set version for next development iteration 2018-09-30 21:05:57 +03:00
26d6d96f78 Reach milestone 1.20.0 2018-09-30 21:03:48 +03:00
3cec7a9ec1 Merge pull request #796 from LyndonArmitage/module-ignore-test-output
Delete & Ignore output.txt & error.txt
2018-09-25 22:49:25 +03:00
b079aec1fd Merge pull request #794 from iluwatar/Issue781
#781 Resolved ClasscastException from Acyclic Visitor
2018-09-25 22:45:25 +03:00
8f53df91b9 Delete & Ignore output.txt & error.txt
Both output.txt and error.txt are produced by tests.
Each file contained a header that was overridden upon executing said
tests causing tracked files to be changed.

Added them to a local .gitignore file for this module.
2018-09-24 10:08:02 +01:00
709405d964 Resolved checkstyle issues 2018-09-11 16:11:59 +05:30
f3749a2b9d Solved the classcast exception and used instanceof instead. Improved javadocs a bit. 2018-09-11 15:58:14 +05:30
1d12d94bac Fix redundant list alloc in LotteryNumbers 2018-09-11 11:55:53 +02:00
9e56e5cbc1 Merge pull request #791 from er2/executeAroundLambda
Execute Around - use lambda
2018-09-09 00:24:42 +05:30
1698b066f3 Merge pull request #767 from nikhilbarar/collection-pipeline
#564: Collection Pipeline pattern
2018-09-09 00:21:45 +05:30
4ed039d807 Updated UCLS file and PNG image 2018-09-08 20:38:04 +05:30
ec6d2a8ebe execute around lambda 2018-09-07 22:29:51 -04:00
98c3f93e82 Review changes in Test Cases 2018-09-04 20:52:11 +05:30
26fbbed62e Typo in Readme 2018-09-01 15:48:36 +05:30
0f9089dd62 Typo in Readme 2018-09-01 15:48:07 +05:30
038befea26 Merge pull request #779 from mitchellirvin/bst-iterator
#778: Binary Search Tree Iterator
2018-08-30 12:46:13 +05:30
9daa3140e4 Category Enum for category of Car 2018-08-29 22:02:17 +05:30
8458e426bc correcting raw types for the item Iterator. 2018-08-29 07:36:52 -04:00
e6f84f2f41 modified return type of TreasureChestItemIterator's constructor to be Iterator 2018-08-28 07:46:02 -04:00
74f3799eb4 Merge pull request #788 from diffblue-assistant/finallyclosetotrywithresources
Use try-with-resources
2018-08-28 13:17:16 +05:30
b23d8430af Added Missing class 2018-08-26 23:31:03 +05:30
cb6b0b3600 Checkstyle Fixes 2018-08-26 23:21:25 +05:30
cd44ef3c81 Review Changes 2018-08-26 23:12:33 +05:30
1c2ddfad54 Refactored App.java to remove duplicate code and elegantly demonstrate each implementation of the Iterator interface. Removed the redundant ItemIterator interface. Added insert() method to TreeNode class to allow for more elegant construction of BSTs. 2018-08-25 18:49:43 -04:00
f36de036f6 Use try-with-resources
Replace try statements that close a resource in the finally block with a
try-with-resources statement [1].

This commit was created automatically by Diffblue refactorings (https://www.diffblue.com/).

[1] https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
2018-08-23 13:44:55 +01:00
b64262303a Merge pull request #787 from bordoisila1/checkstyle-minor-updates
Fixed minor changes suggested by Checkstyle
2018-08-21 11:20:16 +05:30
9d012772fd Merge pull request #785 from sgyyz/fix-image-name
Fix converter image Display Issue
2018-08-21 11:12:40 +05:30
e1a2f141c5 Fixed minor changes suggested by Checkstyle 2018-08-20 22:36:58 -04:00
cce104a271 Fix converter image issue 2018-08-20 21:14:16 +08:00
16df157181 Add license headers 2018-08-13 08:13:06 +03:00
c34004bea5 Merge pull request #763 from 7agustibm/master
First proposal for #586 Hexagonal Architecture primary ports should have interfaces
2018-08-10 22:42:09 +03:00
3e0cfa5684 #778 Implemented BSTIterator. Included comprehensive unit and integration tests. Refactored file structure to be friendly to future contributors with iterators of more data structures. Added JUnitPlatform to enable running test suite across all iterator implementations. Added README to /binarysearchtree to document what it does and how it works. 2018-08-04 21:59:53 -04:00
ce459e8f9f Merge branch 'master' into collection-pipeline
# Conflicts:
#	pom.xml
2018-08-02 02:43:47 +05:30
535431fac1 Merge branch 'master' of https://github.com/iluwatar/java-design-patterns 2018-08-02 02:30:08 +05:30
facb9e51a6 Merge pull request #774 from zenuo/master
Add an 'Override' annotaion
2018-08-01 16:02:23 +03:00
9eb8c30bcb Add Annotation 'Override' to com.iluwatar.reactor.app.AppClient.TcpLoggingClient.run method. 2018-07-18 17:06:19 +08:00
fc87f8b7d3 Merge branch 'master' of https://github.com/iluwatar/java-design-patterns
# Conflicts:
#	pom.xml
2018-07-08 23:09:55 +05:30
b453753790 Fix import not used 2018-07-08 19:38:54 +02:00
d2b900b524 Fix checkstyle & update interface services 2018-07-08 19:25:42 +02:00
2c8d1744df #564: Collection Pipeline pattern 2018-07-08 21:37:30 +05:30
d915b66e70 Merge pull request #755 from okinskas/ambassador
Ambassador Pattern #722
2018-07-08 09:55:36 +03:00
328f917749 #564: Collection Pipeline pattern 2018-07-02 00:42:04 +05:30
ae07423470 First proposal 2018-07-01 16:29:07 +02:00
7add7b833c Merge branch 'master' into ambassador 2018-06-29 14:34:31 +01:00
c7f9266768 Merge pull request #753 from Argyro-Sioziou/master
Acyclic Visitor pattern #734
2018-06-28 13:55:32 +05:30
0453bf9063 General cleanup. Simplifying code. Replacing all prints with appropriate Logger. 2018-06-23 13:24:07 +01:00
f9bdd58bb7 Merge remote-tracking branch 'upstream/master' 2018-06-14 18:34:27 +03:00
57f60c5ebf Updating javadoc comments 2018-06-14 18:30:46 +03:00
51659fe9c5 Updating HayesVisitor and ZoomVisitor 2018-06-14 18:04:30 +03:00
04d80f05c8 Adding consequences in README.md 2018-06-14 17:56:14 +03:00
6636fb151b Adding AllModemVisitor interface 2018-06-14 12:40:41 +03:00
6a0fa747ad Fixing typos 2018-06-14 12:18:46 +03:00
8b1ed95d6b Updating ConfigureForDosVisitorTest and ConfigureForUnixVisitorTest classes 2018-06-14 12:14:35 +03:00
6167d06dce Removing test case 2018-06-14 12:02:34 +03:00
49feead13f Removing interfaces' test classes 2018-06-14 11:59:02 +03:00
179a02bcdd Removing default constructors 2018-06-14 11:52:23 +03:00
71f61cd40e #466, #509: Added diagrams and Readme files 2018-06-13 23:40:36 +05:30
d54e29051f #466: Fix Checkstyle Issues 2018-06-13 02:54:09 +05:30
4456a440bc Monitor Object pattern #466 2018-06-13 02:43:25 +05:30
c48a1e9193 #509: Checkstyle Fixes 2018-06-11 01:56:32 +05:30
971a74e13a #509: Component Object Pattern 2018-06-11 00:38:03 +05:30
868e4561b5 Updating pom dependencies and adding license. 2018-06-05 21:16:16 +01:00
c4dd94a019 Fixing CheckStyle issues in Test classes. 2018-06-05 07:32:29 +01:00
ff579fabcf Fixing CheckStyle issues. 2018-06-04 22:50:59 +01:00
5393c96247 Adding README.md 2018-06-04 22:32:05 +01:00
bae51f5803 Adding license to test classes. 2018-06-04 21:27:04 +01:00
74190e36bb Adding tests for each class. 2018-06-04 21:20:04 +01:00
6b10f4bdd1 Adding appropriate comments on classes and full description in App.java. Removing added function in ServiceAmbassador as it's not appropriate for the example. 2018-06-04 20:36:10 +01:00
73925cef2e Ambassador adds logging, imitates trying to connect to remote service and provides new client-side functionality. Need to clean up code, add tests and add descriptive comments. 2018-06-03 22:20:40 +01:00
987994f0fe Add license headers 2018-06-03 14:15:11 +03:00
95df47e418 Disable intermittently failing test 2018-06-03 14:15:00 +03:00
afe85e22e7 Enhancing code format 2018-05-29 01:37:53 +03:00
4023944240 Adding README.md file 2018-05-27 17:10:20 +03:00
17164c282a Adding class diagram 2018-05-27 17:07:34 +03:00
27f58e0925 Adding HayesTest and ZoomTest 2018-05-27 17:04:22 +03:00
36a14778dc Adding App class 2018-05-27 17:02:56 +03:00
5e1da6361f Adding ConfigureForDosVisitor and ConfigureForUnixVisitor 2018-05-27 16:58:38 +03:00
97718846d1 Adding HayesVisitor and ZoomVisitor 2018-05-27 16:55:08 +03:00
bbdf1cd738 Adding Hayes and Zoom classes 2018-05-27 16:51:26 +03:00
323395daaf Adding ModemVisitorTest 2018-05-27 16:49:05 +03:00
75734a6b7d Adding Modem abstract class 2018-05-27 16:45:43 +03:00
3f92b8f84e Adding ModemTest 2018-05-27 16:37:13 +03:00
18a75c0620 Adding ModemVisitor interface 2018-05-27 16:12:31 +03:00
9e15abbafc Adding pom.xml file 2018-05-27 15:49:35 +03:00
e9a219f643 Merge branch 'master' of https://github.com/Argyro-Sioziou/java-design-patterns into acyclic-visitor 2018-05-27 15:44:04 +03:00
8bf53fe91d Adding acyclic-visitor module in pom.xml 2018-05-27 15:11:06 +03:00
c713dbcbf4 Merge pull request #752 from christophercolumbusdog/master
#643 Fix flaky tests for throttling pattern
2018-05-27 10:59:52 +03:00
f3e1cd3a1d Fix checkstyle 2018-05-25 22:47:23 -05:00
4ab46c7fcb #643 Fix flaky tests for throttling pattern 2018-05-25 22:26:35 -05:00
d7893c1fc2 Updated incorrect tag
Corrected improper tag from Difficulty-Easy to Difficulty-Beginner
2018-05-16 12:36:17 +05:30
eddfe76a84 Merge pull request #717 from waisuan/master
Dirty Flag pattern #560
2018-05-16 12:31:20 +05:30
a386d4266d Fixed UnitTest 2018-05-12 18:18:44 +01:00
29edeabaae Fixes based on code review feedback 2018-05-12 17:47:03 +01:00
abcc39871b Merged with upstream 2018-05-12 16:12:23 +01:00
4ac6f90c96 Merge pull request #748 from pelmegov/clean-converter-class
Parameters in Converter class methods was renamed.
2018-04-29 10:39:51 +03:00
a8d89ca861 Parameters in Converter class methods was renamed. A base class must not contain the concrete entities names or concrete class names 2018-04-28 19:34:57 +03:00
998600f09e Merge pull request #744 from pokemon4e/master
Consistent naming for EIP patterns #733
2018-04-12 21:02:08 +03:00
1e04b17a2d Merge pull request #743 from MottoX/cleanup
Cleanup unnecessary code
2018-04-12 20:39:45 +03:00
187b16c9e0 Merge pull request #740 from mernst/coverage-documentation
Correct the command for computing code coverage
2018-04-12 20:37:30 +03:00
3b45f2cad6 Consistent naming for EIP patterns #733 2018-04-12 15:49:52 +03:00
65e1cae2de Cleanup unnecessary code 2018-04-11 16:11:37 +08:00
0b7343dd34 Correct the command for computing code coverage 2018-04-09 16:38:09 -07:00
379a825182 Merge pull request #714 from dheeraj-mummareddy/master
#473 serveless implementation using aws compute engine and serverless fram…
2018-04-08 20:01:42 +03:00
522fbc035f delete the incorrect package 2018-04-08 10:56:48 -04:00
40e5cc628a minor code review comments and Updating license header 2018-04-08 10:56:10 -04:00
7a13012855 Merge branch 'master' of github.com:iluwatar/java-design-patterns 2018-04-08 10:38:16 -04:00
1c0e0cd88b Set version for next development iteration 2018-03-31 10:36:05 +03:00
3407392664 Reach milestone 1.19.0 2018-03-31 10:34:25 +03:00
474c218f85 Update license headers 2018-03-31 10:25:58 +03:00
17ea0b17f6 Disable flaky tests mentioned in issue #643 and #699 2018-03-31 10:16:56 +03:00
7d4ccc6490 Merge pull request #730 from Deathnerd/master
Add Java annotation to code blocks in README files #728
2018-03-31 09:50:28 +03:00
8b06ea52ab Removed unnecessary changes outside of scope of the task 2018-03-28 01:41:43 -04:00
86ee59c232 Add Java annotation to code blocks in README files 2018-03-28 01:35:43 -04:00
6879990857 Merge pull request #726 from valery1707/patch-1
Update SonarCloud badge
2018-03-24 16:24:05 +02:00
855cf75dd6 Merge pull request #729 from S177LM/patch-1
Fixed typo
2018-03-22 17:38:32 +02:00
ecad864703 Fixed typo
Just fixed a little repetition in the javadoc comment.
2018-03-20 19:51:04 +01:00
c3b102e547 fixing the link 2018-03-14 19:22:39 -04:00
69be74c016 Update SonarCloud badge
Update link into badge URL as described in https://about.sonarcloud.io/news/2018/02/05/new-project-badges.html
2018-03-14 20:20:15 +03:00
3f9a5a254e code review comments 2018-03-13 12:03:23 -04:00
05a9c030c0 Merge branch 'master' of github.com:iluwatar/java-design-patterns 2018-03-12 09:19:55 -04:00
c723289bbb Merge pull request #723 from Juaanma/patch-1
Captain is implementing RowingBoat - Adapter pattern
2018-03-11 21:59:13 +02:00
477da92e2f Merge pull request #724 from anthonycampbell/master
My solution to issue #602.
2018-03-11 21:23:32 +02:00
ac57d67f45 solution to issue #602. Implemented multiton with enum, added example to app.java, a test for the enum, and commented my code 2018-03-08 16:08:09 -08:00
960d2ea6f7 solution to issue #602. Implemented multiton with enum, added example to app.java, a test for the enum, and commented my code 2018-03-08 15:52:35 -08:00
87cb33f69b Fixed tests 2018-03-07 17:43:03 -03:00
915a1f3eb0 Forgot to delete row's @Override
My bad, sorry. It should compile now.
2018-03-07 17:26:39 -03:00
c8fd0bc23d Merge pull request #716 from baislsl/javadoc-fix
Improve Javadoc
2018-03-07 21:52:50 +02:00
696ed86aff Captain is implementing RowingBoat - Adapter pattern
Captain and RowingBoat aren't interchangable. 
Captain, as a client, may have a method to use the boat, but it isn't needed that they share the same interface, as it makes the code more confusing.
2018-03-07 00:19:33 -03:00
e0b8f6f850 fix checkstyle 2018-03-06 16:09:22 +08:00
143213483c fixing typo 2018-03-05 21:41:24 -05:00
678fa93838 update readme and thanks to Amazon Web Services & cloud guru 2018-03-05 21:25:08 -05:00
b2607010b4 update readme and ready for review 2018-03-05 21:23:42 -05:00
b2dd36f607 adding backend as a service with lambda + api gateway + dynamodb 2018-03-05 20:51:32 -05:00
af6973884f merge from upstream and fixing conflicts 2018-03-04 17:46:29 -05:00
3894a0bb6c Merge branch 'master' of github.com:iluwatar/java-design-patterns 2018-03-04 17:33:58 -05:00
49f8434911 Merge branch 'master' of github.com:iluwatar/java-design-patterns 2018-03-04 17:33:27 -05:00
55bbb88ac9 Merge branch 'master' into master 2018-03-04 23:51:04 +08:00
ce88fd723e Merge branch 'master' of https://github.com/waisuan/java-design-patterns 2018-03-04 15:25:55 +00:00
e01d640499 Merge pull request #713 from baislsl/master
Use the @TestInstance annotation
2018-02-25 08:54:00 +02:00
7fef5e4cd5 Merge pull request #696 from besok/master
#677 add pattern Trampoline.
2018-02-25 08:45:36 +02:00
3333a2839b Remove unused var 2018-02-20 10:58:49 +00:00
a60fa76fd9 Add UML diagram 2018-02-20 10:35:06 +00:00
565f5a4e70 Add README.md 2018-02-20 09:48:44 +00:00
b73ef6e6c5 Dirty Flag pattern #560 2018-02-19 16:08:45 +00:00
991ba320a6 Improve Javadoc 2018-02-19 22:01:14 +08:00
d78434fed8 Merge pull request #644 from spanhal1/master
added tutorial links to bridge, decorator, abstract-factory, strategy…
2018-02-17 20:39:52 +02:00
f9f93695fe Merge pull request #609 from igorcadelima/master
Protect against instantiation via reflection
2018-02-17 20:36:40 +02:00
a367832d9e Merge pull request #711 from ryanguest/master
Fix typo
2018-02-17 20:26:26 +02:00
7a7ba871dc serveless implementation using aws compute engine and serverless framework 2018-02-08 12:03:00 -05:00
36f5947cd7 Use the @TestInstance annotation 2018-02-08 03:00:55 +08:00
f62ae456b0 Fix typo 2018-02-01 15:44:23 -08:00
5cbf651a3e Merge branch 'master' into master 2018-01-28 14:44:19 -05:00
e7b119c95c Merge pull request #709 from mookkiah/issue_508_prototype
issue 508 - using copy constructor to implement prototype.
2018-01-28 10:44:25 +02:00
ec28b1250d Merge pull request #708 from BeeHuang/fix-comment
Fix error comment with isServiceRunnign in Event Queue
2018-01-28 10:29:19 +02:00
2dcf63c646 fixed typo in abstract factory pattern 2018-01-27 20:30:15 -05:00
0805716515 issue 508 - using copy constructor to implement prototype.
As per http://www.artima.com/intv/bloch13.html, clone method in java is
broken or confusing. So staying away from clone method.
2018-01-27 09:57:15 -05:00
9f797b3009 fix error comment with isServiceRunnign 2018-01-27 16:44:23 +08:00
33a3d6fef4 Merge pull request #702 from zafarella/patch-4
Add thread safety comment on enum based singleton
2018-01-23 23:24:39 +02:00
dddfb52c70 Update EnumIvoryTower.java 2018-01-23 00:07:11 -05:00
9667878b5f add junit - jupiter -engine 2018-01-20 22:09:42 +03:00
4c4cbd41cf fix checkstyle errors 2018-01-20 21:42:14 +03:00
f7825f6c99 changes fixing mistakes 2018-01-20 13:36:43 +03:00
8960ef6111 Merge pull request #698 from olcbean/redundant_super
Remove redundant explicit super() constructor calls #694
2018-01-16 21:22:20 +02:00
a82000650d Remove redundant explicit super() constructor calls #694 2018-01-15 19:33:55 +01:00
e9021329e1 Merge pull request #697 from james-a-roland/issue_694
Removing all redundant super constructor calls, issue 694.
2018-01-13 22:25:31 +02:00
e9a541259b Removing all redundant super constructor calls 2018-01-10 21:20:37 -08:00
94fdefee3a add code 2018-01-08 14:45:38 +03:00
b61b64073a #677 init folder for pattern trampoline 2018-01-08 14:00:12 +03:00
09c0891948 Merge pull request #693 from jujis008/master
fixed issue #681
2018-01-08 07:55:39 +02:00
90570f809b rename png file and changes for README.md 2018-01-08 11:09:04 +08:00
55be744c4a #674 update SonarQube badge URL and link 2018-01-07 21:34:15 +02:00
c34975bdff #674 update SonarQube analysis URL 2018-01-07 21:25:00 +02:00
ed37d5cdc7 regenerate UML diagram 2018-01-07 12:26:58 +08:00
f87754917c Merge pull request #690 from amogozov/master
Cleanup commented code
2018-01-02 19:29:14 +02:00
e046007db7 fixed issue #681 2018-01-02 18:23:11 +08:00
0306161380 Cleanup commented code 2018-01-02 09:24:18 +09:00
dea2316f1f Set version for next development iteration 2018-01-01 16:58:29 +02:00
cb38501ea2 Reach milestone 1.18.0 2018-01-01 16:50:05 +02:00
7f959ed157 Merge pull request #689 from amogozov/junit5-migration
Migrate to JUnit5
2018-01-01 16:42:47 +02:00
6694d742a3 Migrate to JUnit5 2017-12-31 16:29:48 +09:00
a20e54d0a7 Fix Retry pattern categories and tags 2017-12-30 10:46:14 +02:00
e8496c5d48 Merge pull request #688 from ThatGuyWithTheHat/master
Event-Asynchronous Class Diagram Corrected.
2017-12-30 10:39:16 +02:00
3defc1b36a Merge remote-tracking branch 'upstream/master' 2017-12-30 08:13:33 -06:00
9677cc4eea Pattern push 2017-12-30 08:10:42 -06:00
fc690869db I messed up the file format. This is the correct version. 2017-12-30 07:42:33 -06:00
37c9b922a7 Corrected Event Asynchonous Class Diagram
Lots of issues but I think this finally has it sorted out!
2017-12-30 07:40:23 -06:00
0824529471 Merge pull request #684 from llorllale/master
#451 Retry pattern
2017-12-30 09:53:28 +02:00
235fe6a7ca DIIIIEEE 2017-12-30 01:32:05 -06:00
5373214b70 Why doesn't this go away? 2017-12-30 01:31:37 -06:00
93c54a2ee5 Try 2 2017-12-30 07:27:29 -06:00
5a930f6a26 new Event Asynchronous file. This one works I hope. 2017-12-30 07:25:22 -06:00
2a4edad23a (FIX) Deleted unused files accidentally added in last commit 2017-12-29 09:42:32 -04:00
c1ea04e002 Upon reviewer's request:
(FIX) Deleted .puml file (no longer required or used)
(FIX) Removed @since annotations (they add noise)
2017-12-29 09:35:57 -04:00
10c0879d3b (FIX) Upgrade all @since versions to 1.18.0 following the
parent pom's version update
2017-12-27 16:09:34 -04:00
620f408688 (FIX) Parent pom version 2017-12-27 16:06:26 -04:00
2456b9f4b0 (FIX) The 'retry' module was not added to the module list in parent pom 2017-12-27 15:46:46 -04:00
144db43ad4 Merge branch 'master' of https://github.com/iluwatar/java-design-patterns 2017-12-27 15:22:02 -04:00
f7c396b0fd (NEW) Module "retry"
(NEW) Illustrative classes:
      - App: simulates a production application
      - BusinessOperation<T>: abstraction over any operation that can
        potentially fail
      - FindCustomer <: BusinessOperation<String>: illustrative
        operation that can throw an error
      - Retry <: BusinessOperation<T>: transparently implements the
        retry mechanism
      - Several "business" exceptions:
        - BusinessException: top-level
        - CustomerNotFoundException: can be ignored
        - DatabaseNotAvailableException: fatal error
(NEW) .puml and .png for UML
2017-12-27 15:15:04 -04:00
6b4ae0d0b1 Merge pull request #682 from zafarella/patch-3
add CII Best Practices badge
2017-12-26 18:28:20 +02:00
04f2be64c6 Update README.md
add CII Best Practices badge
2017-12-25 08:52:52 -05:00
6c4de3bcef Fix some tags and categories 2017-12-25 11:30:24 +02:00
a2d155cbb9 Merge pull request #680 from fanofxiaofeng/patch-3
replace 'a' with 'an'
2017-12-15 21:27:11 +02:00
52f09d043c Merge pull request #679 from fanofxiaofeng/patch-2
fix typo
2017-12-15 21:26:32 +02:00
11de22bf4a Merge pull request #678 from Tschis/presentations
Add presentation for Command and Factory Method
2017-12-15 21:25:49 +02:00
6614d0735e Merge pull request #671 from zafarella/patch-2
Create PULL_REQUEST_TEMPLATE.md
2017-12-15 21:24:00 +02:00
8312e09f6e replace 'a' with 'an'
[A or An](https://www.a-or-an.com/a_an/axe)
2017-12-14 16:15:02 +08:00
176bb85f40 fix typo
'exepcted'->'expected'
'expectedVisibilty'->'expectedVisibility'
2017-12-12 20:40:16 +08:00
7e7a0c83f5 Update readme with presentation link 2017-12-11 13:48:29 -03:00
4dbf646b37 Add Command presentation 2017-12-11 13:45:10 -03:00
506d316529 Add Factory Method presentation 2017-12-11 11:45:32 -03:00
8a9162f542 Update PULL_REQUEST_TEMPLATE.md 2017-12-09 16:25:27 -05:00
4b1650fbde Merge pull request #676 from Tschis/master
Add presentation for Abstract Factory
2017-12-09 22:38:28 +02:00
d26f2620ec Merge pull request #668 from Krandelbord/master
added synchronized keyword to method that reads from server poll
2017-12-09 22:29:40 +02:00
fb5c2a0324 Merge pull request #642 from piyushchaudhari04/unit-of-work-pattern
#352 - Unit of work pattern implementation
2017-12-04 00:32:49 +05:30
7cf897a051 Add presentation for Abstract Factory 2017-11-30 15:15:10 -03:00
171c4b30b9 #190 Remove puml posting script 2017-11-28 21:30:45 +02:00
bf98299db2 #190 Remove pumlids from readmes 2017-11-28 21:28:53 +02:00
b0f9582824 #190 Remove urm plugin 2017-11-28 20:55:52 +02:00
fb64d69347 Create PULL_REQUEST_TEMPLATE.md 2017-11-25 00:03:34 -05:00
4450000a83 Merge pull request #665 from Tschis/master
(Abstract Factory) Add factory of factories
2017-11-20 16:26:44 +02:00
14279278cd Sync readme.md with the new code 2017-11-19 19:22:03 -02:00
071cde8d70 Add license headers 2017-11-19 20:17:57 +02:00
6339e26838 Merge pull request #663 from codinghog/master
#114 Added eip-aggregator
2017-11-19 19:43:21 +02:00
5c953d7d00 added synchronized keyword to method that reads from server poll 2017-11-19 12:01:39 +01:00
51096ec445 #352- Unit Of Work : Update java doc for methods. 2017-11-12 15:50:12 +05:30
f3f1f54ccc #352- Unit Of Work : Update parent module version in unit of work module. 2017-11-12 15:19:49 +05:30
f58256d70a #352- Unit Of Work : Updated applicability of pattern in README. 2017-11-12 15:09:47 +05:30
933c84ff1c Fix checkstyle validations 2017-11-07 22:32:36 -03:00
3634b3338c Fix checkstyle validations 2017-11-07 22:19:10 -03:00
d37922bf82 add factory of factories 2017-11-07 21:05:04 -03:00
87ee97a112 #114 Fixed checkstyle issue 2017-11-07 07:37:12 +01:00
c45e9a1faf #114 Fixed checkstyle issue 2017-11-07 07:24:31 +01:00
390c33e36e Merge pull request #661 from hukacode/patch-1
Fix typo
2017-11-05 09:59:14 +02:00
5f90b2597a Merge pull request #659 from pechenoha/master
Fix a typo in the "Facade" pattern
2017-11-05 09:51:40 +02:00
6e0bf59e5a #114 Aggregator pattern; tests; description 2017-11-04 22:38:51 +01:00
7185830700 Merge branch 'unit-of-work-pattern' of github.com:piyushchaudhari04/java-design-patterns into unit-of-work-pattern 2017-10-31 16:31:01 +05:30
ec6eea61a5 #352- Unit Of Work : Updated applicability of pattern in README. 2017-10-31 16:26:24 +05:30
89bfaf876e Fix typo 2017-10-31 17:32:11 +07:00
e289779dd3 Fix a typo 2017-10-30 19:54:31 +02:00
a2a13758e0 Merge branch 'master' of https://github.com/iluwatar/java-design-patterns 2017-10-28 22:27:34 +02:00
5ed46c2c64 Merge pull request #656 from bjurga/bjurga-App.java-patch
Use UserConverter instead of rewriting its ctor
2017-10-22 22:21:54 +03:00
168c9cf3a9 Merge pull request #655 from codinghog/master
#173 Added new pattern - EIP Splitter
2017-10-22 22:17:51 +03:00
0312392b3c Merge pull request #654 from fanofxiaofeng/patch-1
maybe it should be "Let's" here
2017-10-22 22:14:37 +03:00
df04e19994 Use UserConverter instead of rewriting its ctor 2017-10-20 13:59:42 +02:00
8c15b89295 Merge branch 'master' into unit-of-work-pattern 2017-10-19 13:03:16 +05:30
eeaf7e4b7c Merge branch 'master' of https://github.com/iluwatar/java-design-patterns 2017-10-17 12:46:54 +02:00
dd828bcd6c #173 Update pom 2017-10-17 12:46:28 +02:00
0aa84e37f2 #173 Pattern description 2017-10-17 12:42:41 +02:00
767f41ad90 #173 Removed unneeded dependencies 2017-10-17 00:12:41 +02:00
9c7ee5ed1d #173 Added new pattern, tests 2017-10-16 19:33:15 +02:00
141d448c17 maybe it should be "Let's" here 2017-10-16 15:37:13 +08:00
41710cbe9e Merge pull request #651 from codinghog/master
#176 Added new pattern - EIP Wire Tap
2017-10-16 08:24:46 +03:00
04dd93f8bc Merge branch 'master' of https://github.com/iluwatar/java-design-patterns 2017-10-15 18:45:36 +02:00
624a4ef857 #176 Fixed CheckStyle issue 2017-10-13 14:22:48 +02:00
0453ba1315 #176 Test run, app shutdown, minor refactoring 2017-10-13 14:02:03 +02:00
60f07d1940 Added test class for App 2017-10-12 17:33:03 +02:00
dfb43299a8 Merge pull request #652 from yosfik/master
Fix FactoryMethodTest and PrototypeTest
2017-10-12 17:13:57 +03:00
b2dd175851 Merge pull request #648 from Peter-Morawski/patch-1
added missing whitespace to the elements of the unordered list
2017-10-09 11:00:43 +05:30
31120a8fa0 Merge pull request #646 from rastdeepanshu/master
Modifications for intermittent test failure in Throttling pattern.
2017-10-09 10:58:57 +05:30
ed1852a789 Fix unused generic type in PrototypeTest 2017-10-08 20:41:28 +07:00
56ba78a5e9 fix test message 2017-10-07 20:33:24 +07:00
522721559b #176 pattern description and diagram 2017-10-04 17:20:29 +02:00
f80d903cff Wire Tap EIP implementation and tests 2017-10-04 17:04:32 +02:00
0d4a8db114 Set version for next development iteration 2017-09-30 22:30:34 +03:00
4e236f6da8 Minor modification of Long to long 2017-09-28 15:04:32 +02:00
4abef6da33 added missing whitespace to the elements of the unordered list 2017-09-26 20:51:32 +02:00
b5eca2f856 #352- Unit Of Work : Updated applicability of pattern in README. 2017-09-27 00:04:06 +05:30
b8491436dd #352- Unit Of Work : modified readme. 2017-09-26 23:25:36 +05:30
04891e5bf3 Merge branch 'unit-of-work-pattern' of github.com:piyushchaudhari04/java-design-patterns into unit-of-work-pattern 2017-09-26 00:07:03 +05:30
244e9c7caa #352- Unit Of Work : modified readme. 2017-09-25 21:23:12 +05:30
01b85b9721 Used AtomicLong for concurrenthashmap operations 2017-09-25 12:59:39 +02:00
e6342d5956 Merge pull request #1 from iluwatar/master
upstream update
2017-09-24 21:55:34 +02:00
e4b0153ddc Merge branch 'master' into unit-of-work-pattern 2017-09-24 13:47:40 +05:30
8e73728fde #352- Unit Of Work : modified readme. 2017-09-24 12:56:06 +05:30
684cad9beb added tutorial links to bridge, decorator, abstract-factory, strategy and template method patterns 2017-09-23 20:55:38 -04:00
a1ee8859d6 #352- Unit Of Work : Update puml diagram. 2017-09-23 00:53:45 +05:30
677f020813 #352- Unit Of Work : Add class diagram. 2017-09-23 00:49:01 +05:30
00dcf24e16 #352- Unit Of Work : Update licence. 2017-09-23 00:34:45 +05:30
1fb0525c6e #352- Unit Of Work : Remove affected lines. 2017-09-23 00:30:18 +05:30
633d3a97a0 #352- Unit Of Work : Add AppTest 2017-09-23 00:18:06 +05:30
9ee2255c1f #352- Unit Of Work : [Refactor] Rename main class to App 2017-09-23 00:15:32 +05:30
bf700fd995 #352- Unit Of Work : Make final instance variable of immutable Student class. 2017-09-23 00:14:13 +05:30
1dc143abca #352- Unit Of Work : Update puml diagram. 2017-09-19 22:49:09 +05:30
530b9e9662 #352- Unit Of Work : added the readme file 2017-09-19 20:39:48 +05:30
2c9098aecc #352- Unit Of Work : added the launching point of the module 2017-09-18 22:31:13 +05:30
5fe9d2be6c #352- Unit Of Work : [Refactor] Change module name to unit-of-work. 2017-09-16 21:39:26 +05:30
68ed2a4726 #352- Unit Of Work : Impement unit of work contract. 2017-09-16 21:35:27 +05:30
acc2fad818 #352- Unit Of Work : Added commit contract in Unit of work. 2017-09-16 18:43:35 +05:30
8a53a2626e #352- Unit Of Work : Unit of work contract. 2017-09-16 18:38:48 +05:30
e43b6f13fd #352- Unit Of Work : Add Student model and puml diagram 2017-09-16 18:11:00 +05:30
4ecc337c7d #352- Unit Of Work : Added module to project. 2017-09-16 17:20:51 +05:30
3c6f7aa046 Protect against instantiation via reflection
Signed-off-by: Igor C. A. de Lima <igorcadelima@gmail.com>
2017-08-12 12:11:10 -03:00
8953bfc81b Merge pull request #1 from iluwatar/master
Bringing fork up-to-date
2016-08-01 16:55:27 +01:00
1020 changed files with 21579 additions and 9373 deletions

15
.sonarcloud.properties Normal file
View File

@ -0,0 +1,15 @@
# Path to sources
#sonar.sources=.
#sonar.exclusions=
#sonar.inclusions=
# Path to tests
#sonar.tests=
#sonar.test.exclusions=
#sonar.test.inclusions=
# Source encoding
#sonar.sourceEncoding=UTF-8
# Exclusions for copy-paste detection
#sonar.cpd.exclusions=

View File

@ -1,4 +1,5 @@
language: java
dist: trusty # Xenial build environment won't allow installation of Java 8
jdk:
- oraclejdk8
@ -17,7 +18,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 +37,4 @@ notifications:
on_failure: always # options: [always|never|change] default: always
on_start: never # options: [always|never|change] default: always
sudo: required
sudo: required

View File

@ -1,13 +1,13 @@
# 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
Please note that the above folder is created under each of the modules. For example:
* adapter/target/site/jacoco/index.html
* busniess-delegate/target/site/jacoco/index.html
* business-delegate/target/site/jacoco/index.html

15
PULL_REQUEST_TEMPLATE.md Normal file
View 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

View File

@ -7,17 +7,17 @@
[![Build status](https://travis-ci.org/iluwatar/java-design-patterns.svg?branch=master)](https://travis-ci.org/iluwatar/java-design-patterns)
[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md)
[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Quality Gate](https://sonarqube.com/api/badges/gate?key=com.iluwatar%3Ajava-design-patterns)](https://sonarqube.com/dashboard/index/com.iluwatar%3Ajava-design-patterns)
[![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=alert_status)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)
# Introduction
Design patterns are formalized best practices that the programmer can use to
Design patterns are the best formalized practices a programmer can use to
solve common problems when designing an application or system.
Design patterns can speed up the development process by providing tested, proven
development paradigms.
Reusing design patterns helps to prevent subtle issues that can cause major
Reusing design patterns help prevent subtle issues which cause major
problems, and it also improves code readability for coders and architects who
are familiar with the patterns.

View File

@ -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)

View File

@ -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
![alt text](./etc/abstract-document-base.png "Abstract Document Base")
![alt text](./etc/abstract-document.png "Abstract Document Traits and Domain")

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View File

@ -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

View File

@ -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">

View File

@ -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

View File

@ -29,14 +29,14 @@
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.17.0</version>
<version>1.21.0</version>
</parent>
<artifactId>abstract-document</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
</project>

View File

@ -54,17 +54,16 @@ public abstract class AbstractDocument implements Document {
@Override
public <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor) {
Optional<List<Map<String, Object>>> any = Stream.of(get(key)).filter(el -> el != null)
Optional<List<Map<String, Object>>> any = Stream.of(get(key)).filter(Objects::nonNull)
.map(el -> (List<Map<String, Object>>) el).findAny();
return any.isPresent() ? any.get().stream().map(constructor) : Stream.empty();
return any.map(maps -> maps.stream().map(constructor)).orElseGet(Stream::empty);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(getClass().getName()).append("[");
properties.entrySet()
.forEach(e -> builder.append("[").append(e.getKey()).append(" : ").append(e.getValue()).append("]"));
properties.forEach((key, value) -> builder.append("[").append(key).append(" : ").append(value).append("]"));
builder.append("]");
return builder.toString();
}

View File

@ -22,18 +22,16 @@
*/
package com.iluwatar.abstractdocument;
import com.iluwatar.abstractdocument.domain.Car;
import com.iluwatar.abstractdocument.domain.HasModel;
import com.iluwatar.abstractdocument.domain.HasParts;
import com.iluwatar.abstractdocument.domain.HasPrice;
import com.iluwatar.abstractdocument.domain.HasType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.iluwatar.abstractdocument.domain.Car;
import com.iluwatar.abstractdocument.domain.enums.Property;
/**
* The Abstract Document pattern enables handling additional, non-static
* properties. This pattern uses concept of traits to enable type safety and
@ -55,20 +53,20 @@ public class App {
LOGGER.info("Constructing parts and car");
Map<String, Object> carProperties = new HashMap<>();
carProperties.put(HasModel.PROPERTY, "300SL");
carProperties.put(HasPrice.PROPERTY, 10000L);
carProperties.put(Property.MODEL.toString(), "300SL");
carProperties.put(Property.PRICE.toString(), 10000L);
Map<String, Object> wheelProperties = new HashMap<>();
wheelProperties.put(HasType.PROPERTY, "wheel");
wheelProperties.put(HasModel.PROPERTY, "15C");
wheelProperties.put(HasPrice.PROPERTY, 100L);
wheelProperties.put(Property.TYPE.toString(), "wheel");
wheelProperties.put(Property.MODEL.toString(), "15C");
wheelProperties.put(Property.PRICE.toString(), 100L);
Map<String, Object> doorProperties = new HashMap<>();
doorProperties.put(HasType.PROPERTY, "door");
doorProperties.put(HasModel.PROPERTY, "Lambo");
doorProperties.put(HasPrice.PROPERTY, 300L);
doorProperties.put(Property.TYPE.toString(), "door");
doorProperties.put(Property.MODEL.toString(), "Lambo");
doorProperties.put(Property.PRICE.toString(), 300L);
carProperties.put(HasParts.PROPERTY, Arrays.asList(wheelProperties, doorProperties));
carProperties.put(Property.PARTS.toString(), Arrays.asList(wheelProperties, doorProperties));
Car car = new Car(carProperties);

View File

@ -25,16 +25,15 @@ package com.iluwatar.abstractdocument.domain;
import java.util.Optional;
import com.iluwatar.abstractdocument.Document;
import com.iluwatar.abstractdocument.domain.enums.Property;
/**
* HasModel trait for static access to 'model' property
*/
public interface HasModel extends Document {
String PROPERTY = "model";
default Optional<String> getModel() {
return Optional.ofNullable((String) get(PROPERTY));
return Optional.ofNullable((String) get(Property.MODEL.toString()));
}
}

View File

@ -25,16 +25,16 @@ package com.iluwatar.abstractdocument.domain;
import java.util.stream.Stream;
import com.iluwatar.abstractdocument.Document;
import com.iluwatar.abstractdocument.domain.enums.Property;
/**
* HasParts trait for static access to 'parts' property
*/
public interface HasParts extends Document {
String PROPERTY = "parts";
default Stream<Part> getParts() {
return children(PROPERTY, Part::new);
return children(Property.PARTS.toString(), Part::new);
}
}

View File

@ -25,16 +25,16 @@ package com.iluwatar.abstractdocument.domain;
import java.util.Optional;
import com.iluwatar.abstractdocument.Document;
import com.iluwatar.abstractdocument.domain.enums.Property;
/**
* HasPrice trait for static access to 'price' property
*/
public interface HasPrice extends Document {
String PROPERTY = "price";
default Optional<Number> getPrice() {
return Optional.ofNullable((Number) get(PROPERTY));
return Optional.ofNullable((Number) get(Property.PRICE.toString()));
}
}

View File

@ -22,19 +22,19 @@
*/
package com.iluwatar.abstractdocument.domain;
import com.iluwatar.abstractdocument.Document;
import java.util.Optional;
import com.iluwatar.abstractdocument.Document;
import com.iluwatar.abstractdocument.domain.enums.Property;
/**
* HasType trait for static access to 'type' property
*/
public interface HasType extends Document {
String PROPERTY = "type";
default Optional<String> getType() {
return Optional.ofNullable((String) get(PROPERTY));
return Optional.ofNullable((String) get(Property.TYPE.toString()));
}
}

View File

@ -0,0 +1,33 @@
/**
* 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.
*/
package com.iluwatar.abstractdocument.domain.enums;
/**
*
* Enum To Describe Property type
*
*/
public enum Property {
PARTS, TYPE, PRICE, MODEL
}

View File

@ -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,9 @@ 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;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* AbstractDocument test class
@ -81,8 +82,8 @@ public class AbstractDocumentTest {
Map<String, Object> props = new HashMap<>();
props.put(KEY, VALUE);
DocumentImplementation document = new DocumentImplementation(props);
assertNotNull(document.toString().contains(KEY));
assertNotNull(document.toString().contains(VALUE));
assertTrue(document.toString().contains(KEY));
assertTrue(document.toString().contains(VALUE));
}
}

View File

@ -22,7 +22,7 @@
*/
package com.iluwatar.abstractdocument;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Simple App test

View File

@ -22,19 +22,17 @@
*/
package com.iluwatar.abstractdocument;
import com.iluwatar.abstractdocument.domain.Car;
import com.iluwatar.abstractdocument.domain.HasModel;
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 static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static junit.framework.TestCase.assertEquals;
import org.junit.jupiter.api.Test;
import com.iluwatar.abstractdocument.domain.Car;
import com.iluwatar.abstractdocument.domain.Part;
import com.iluwatar.abstractdocument.domain.enums.Property;
/**
* Test for Part and Car
@ -51,9 +49,9 @@ public class DomainTest {
@Test
public void shouldConstructPart() {
Map<String, Object> partProperties = new HashMap<>();
partProperties.put(HasType.PROPERTY, TEST_PART_TYPE);
partProperties.put(HasModel.PROPERTY, TEST_PART_MODEL);
partProperties.put(HasPrice.PROPERTY, TEST_PART_PRICE);
partProperties.put(Property.TYPE.toString(), TEST_PART_TYPE);
partProperties.put(Property.MODEL.toString(), TEST_PART_MODEL);
partProperties.put(Property.PRICE.toString(), TEST_PART_PRICE);
Part part = new Part(partProperties);
assertEquals(TEST_PART_TYPE, part.getType().get());
@ -64,9 +62,9 @@ public class DomainTest {
@Test
public void shouldConstructCar() {
Map<String, Object> carProperties = new HashMap<>();
carProperties.put(HasModel.PROPERTY, TEST_CAR_MODEL);
carProperties.put(HasPrice.PROPERTY, TEST_CAR_PRICE);
carProperties.put(HasParts.PROPERTY, Arrays.asList(new HashMap<>(), new HashMap<>()));
carProperties.put(Property.MODEL.toString(), TEST_CAR_MODEL);
carProperties.put(Property.PRICE.toString(), TEST_CAR_PRICE);
carProperties.put(Property.PARTS.toString(), Arrays.asList(new HashMap<>(), new HashMap<>()));
Car car = new Car(carProperties);
assertEquals(TEST_CAR_MODEL, car.getModel().get());

View File

@ -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)

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

View 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](diagram1.png)]
---
# 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[![Diagram](diagram2.png)]
---
# 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://remarkjs.com/downloads/remark-latest.min.js">
</script>
<script>
var slideshow = remark.create();
</script>
</body>
</html>

View File

@ -29,13 +29,13 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.17.0</version>
<version>1.21.0</version>
</parent>
<artifactId>abstract-factory</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

View File

@ -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());
}
}
}

View File

@ -29,14 +29,17 @@ package com.iluwatar.abstractfactory;
*/
public class ElfKingdomFactory implements KingdomFactory {
@Override
public Castle createCastle() {
return new ElfCastle();
}
@Override
public King createKing() {
return new ElfKing();
}
@Override
public Army createArmy() {
return new ElfArmy();
}

View File

@ -29,14 +29,17 @@ package com.iluwatar.abstractfactory;
*/
public class OrcKingdomFactory implements KingdomFactory {
@Override
public Castle createCastle() {
return new OrcCastle();
}
@Override
public King createKing() {
return new OrcKing();
}
@Override
public Army createArmy() {
return new OrcArmy();
}

View File

@ -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

View File

@ -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
View File

@ -0,0 +1,39 @@
---
layout: pattern
title: Acyclic Visitor
folder: acyclic-visitor
permalink: /patterns/acyclic-visitor/
categories: Behavioral
tags:
- Java
- Difficulty-Intermediate
---
![alt text](./etc/acyclic-visitor.png "Acyclic Visitor")
## 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)

View 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>

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

71
acyclic-visitor/pom.xml Normal file
View File

@ -0,0 +1,71 @@
<!--
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.21.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-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>

View File

@ -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{
}

View File

@ -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 Dos 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
}
}

View File

@ -0,0 +1,45 @@
/**
* 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);
@Override
public void visit(Hayes hayes) {
LOGGER.info(hayes + " used with Dos configurator.");
}
@Override
public void visit(Zoom zoom) {
LOGGER.info(zoom + " used with Dos configurator.");
}
}

View File

@ -0,0 +1,41 @@
/**
* 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);
@Override
public void visit(Zoom zoom) {
LOGGER.info(zoom + " used with Unix configurator.");
}
}

View File

@ -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";
}
}

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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.
}

View File

@ -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";
}
}

View File

@ -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);
}

View File

@ -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);
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,57 @@
/**
* 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 org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import uk.org.lidalia.slf4jtest.TestLogger;
import uk.org.lidalia.slf4jtest.TestLoggerFactory;
/**
* ConfigureForUnixVisitor test class
*/
public class ConfigureForUnixVisitorTest {
private static final 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."));
}
}

View File

@ -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);
}
}

View File

@ -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));
}
}

View File

@ -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();
```

View File

@ -29,13 +29,13 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.17.0</version>
<version>1.21.0</version>
</parent>
<artifactId>adapter</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -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();
}

View File

@ -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();

View File

@ -22,7 +22,7 @@
*/
package com.iluwatar.adapter;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;

View File

@ -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

View File

@ -29,7 +29,7 @@
<parent>
<artifactId>aggregator-microservices</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.17.0</version>
<version>1.21.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -54,8 +54,8 @@
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@ -85,4 +85,4 @@
</plugin>
</plugins>
</build>
</project>
</project>

View File

@ -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);
}

View File

@ -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

View File

@ -1,12 +0,0 @@
@startuml
package com.iluwatar.information.microservice {
class InformationApplication {
+ InformationApplication()
+ main(args : String[]) {static}
}
class InformationController {
+ InformationController()
+ getProductTitle() : String
}
}
@enduml

View File

@ -1,12 +0,0 @@
@startuml
package com.iluwatar.inventory.microservice {
class InventoryApplication {
+ InventoryApplication()
+ main(args : String[]) {static}
}
class InventoryController {
+ InventoryController()
+ getProductInventories() : int
}
}
@enduml

View File

@ -29,7 +29,7 @@
<parent>
<artifactId>aggregator-microservices</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.17.0</version>
<version>1.21.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -54,8 +54,8 @@
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

View File

@ -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);
}
}

View File

@ -29,7 +29,7 @@
<parent>
<artifactId>aggregator-microservices</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.17.0</version>
<version>1.21.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -54,8 +54,8 @@
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
@ -76,4 +76,4 @@
</plugin>
</plugins>
</build>
</project>
</project>

View File

@ -22,19 +22,20 @@
*/
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
*/
public class InventoryControllerTest {
@Test
public void testGetProductInventories() throws Exception {
public void testGetProductInventories() {
InventoryController inventoryController = new InventoryController();
int numberOfInventories = inventoryController.getProductInventories();
Assert.assertEquals(5, numberOfInventories);
assertEquals(5, numberOfInventories);
}
}

View File

@ -29,32 +29,11 @@
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.17.0</version>
<version>1.21.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
View 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;
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)

43
ambassador/pom.xml Normal file
View File

@ -0,0 +1,43 @@
<?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.21.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ambassador</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View 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);
}
}

View 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;
}
}

View File

@ -0,0 +1,76 @@
/**
* 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 com.iluwatar.ambassador.util.RandomProvider;
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 {
static final int THRESHOLD = 200;
private static final Logger LOGGER = LoggerFactory.getLogger(RemoteService.class);
private static RemoteService service = null;
private final RandomProvider randomProvider;
static synchronized RemoteService getRemoteService() {
if (service == null) {
service = new RemoteService();
}
return service;
}
private RemoteService() {
this(Math::random);
}
/**
* This constuctor is used for testing purposes only.
*/
RemoteService(RandomProvider randomProvider) {
this.randomProvider = randomProvider;
}
/**
* 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 less than {@link RemoteService#THRESHOLD}, it returns value * 10,
* otherwise {@link RemoteServiceInterface#FAILURE}.
*/
@Override
public long doRemoteFunction(int value) {
long waitTime = (long) Math.floor(randomProvider.random() * 1000);
try {
sleep(waitTime);
} catch (InterruptedException e) {
LOGGER.error("Thread sleep state interrupted", e);
}
return waitTime <= THRESHOLD ? value * 10 : FAILURE;
}
}

View File

@ -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.ambassador;
/**
* Interface shared by ({@link RemoteService}) and ({@link ServiceAmbassador}).
*/
interface RemoteServiceInterface {
int FAILURE = -1;
long doRemoteFunction(int value) throws Exception;
}

View File

@ -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 = FAILURE;
for (int i = 0; i < RETRIES; i++) {
if (retries >= RETRIES) {
return FAILURE;
}
if ((result = checkLatency(value)) == FAILURE) {
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;
}
}

View File

@ -0,0 +1,30 @@
/**
* 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.
*/
package com.iluwatar.ambassador.util;
/**
* An interface for randomness. Useful for testing purposes.
*/
public interface RandomProvider {
double random();
}

View File

@ -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[]{});
}
}

View 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.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test for {@link Client}
*/
public class ClientTest {
@Test
public void test() {
Client client = new Client();
long result = client.useService(10);
assertTrue(result == 100 || result == RemoteService.FAILURE);
}
}

View File

@ -0,0 +1,64 @@
/**
* 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 com.iluwatar.ambassador.util.RandomProvider;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test for {@link RemoteService}
*/
public class RemoteServiceTest {
@Test
public void testFailedCall() {
RemoteService remoteService = new RemoteService(
new StaticRandomProvider(0.21));
long result = remoteService.doRemoteFunction(10);
assertEquals(RemoteServiceInterface.FAILURE, result);
}
@Test
public void testSuccessfulCall() {
RemoteService remoteService = new RemoteService(
new StaticRandomProvider(0.2));
long result = remoteService.doRemoteFunction(10);
assertEquals(100, result);
}
private class StaticRandomProvider implements RandomProvider {
private double value;
StaticRandomProvider(double value) {
this.value = value;
}
@Override
public double random() {
return value;
}
}
}

View File

@ -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.ambassador;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test for {@link ServiceAmbassador}
*/
public class ServiceAmbassadorTest {
@Test
public void test() {
long result = new ServiceAmbassador().doRemoteFunction(10);
assertTrue(result == 100 || result == RemoteServiceInterface.FAILURE);
}
}

View File

@ -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

View File

@ -29,7 +29,7 @@
<parent>
<artifactId>api-gateway</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.17.0</version>
<version>1.21.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>api-gateway-service</artifactId>
@ -48,13 +48,17 @@
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@ -62,10 +66,6 @@
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
</dependencies>
<build>
@ -84,4 +84,4 @@
</plugin>
</plugins>
</build>
</project>
</project>

View File

@ -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);
}

View File

@ -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

View File

@ -1,12 +0,0 @@
@startuml
package com.iluwatar.image.microservice {
class ImageApplication {
+ ImageApplication()
+ main(args : String[]) {static}
}
class ImageController {
+ ImageController()
+ getImagePath() : String
}
}
@enduml

View File

@ -1,12 +0,0 @@
@startuml
package com.iluwatar.price.microservice {
class PriceApplication {
+ PriceApplication()
+ main(args : String[]) {static}
}
class PriceController {
+ PriceController()
+ getPrice() : String
}
}
@enduml

View File

@ -29,7 +29,7 @@
<parent>
<artifactId>api-gateway</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.17.0</version>
<version>1.21.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -54,8 +54,8 @@
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
@ -76,4 +76,4 @@
</plugin>
</plugins>
</build>
</project>
</project>

View File

@ -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);
}
}

View File

@ -29,32 +29,11 @@
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.17.0</version>
<version>1.21.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>

View File

@ -29,7 +29,7 @@
<parent>
<artifactId>api-gateway</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.17.0</version>
<version>1.21.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -54,8 +54,8 @@
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
@ -76,4 +76,4 @@
</plugin>
</plugins>
</build>
</project>
</project>

View File

@ -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);
}
}

View File

@ -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

View File

@ -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

View File

@ -29,13 +29,13 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.17.0</version>
<version>1.21.0</version>
</parent>
<artifactId>async-method-invocation</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -22,7 +22,7 @@
*/
package com.iluwatar.async.method.invocation;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
*

View File

@ -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());
}
});
}

View File

@ -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

View File

@ -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

View File

@ -29,18 +29,18 @@
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.17.0</version>
<version>1.21.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-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
</project>

View File

@ -0,0 +1,32 @@
/**
* 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.
*/
package com.iluwatar.balking;
import java.util.concurrent.TimeUnit;
/**
* An interface to simulate delay while executing some work.
*/
public interface DelayProvider {
void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task);
}

Some files were not shown because too many files have changed in this diff Show More