Compare commits

...

129 Commits
1.8.0 ... 1.9.0

Author SHA1 Message Date
e4458c1b17 Achieved milestone 1.9.0 2016-01-01 20:37:50 +02:00
30e09a8dd9 Merge pull request #331 from fluxw42/master
Add unit tests for remaining patterns
2016-01-01 18:24:58 +02:00
f987c7253b Merge pull request #330 from mikulucky/master
Delegation Pattern
2016-01-01 16:49:01 +02:00
ad714294dd Clean up javaDocs on Printer.java #324 2015-12-30 20:08:52 +00:00
623c2081cd Update App.java to have more information on the pattern #324 2015-12-30 20:07:42 +00:00
542a832a66 Added tests for twin pattern 2015-12-30 20:55:22 +01:00
444eb07e26 Added tests for tolerant-reader pattern 2015-12-30 20:55:22 +01:00
fd8c05846f Added tests for thread-pool pattern
Fixed concurrency problem in id generation of Task
2015-12-30 20:55:22 +01:00
47709e24b9 Added tests for template-method pattern 2015-12-30 20:55:22 +01:00
09d3a82884 Added tests for visitor pattern 2015-12-30 20:55:22 +01:00
997bfba3b2 Added tests for strategy pattern 2015-12-30 20:55:22 +01:00
6326c1742d Added tests for step-builder pattern 2015-12-30 20:55:22 +01:00
2e2707862a Fixed checkstyle code quality issues 2015-12-30 20:55:21 +01:00
1d9aff4071 Added tests for state pattern 2015-12-30 20:55:21 +01:00
5611f26c77 Added tests for specification pattern 2015-12-30 20:55:21 +01:00
d0cdf84936 Added tests for singleton pattern 2015-12-30 20:55:21 +01:00
a375b2d28b Added tests for service-locator pattern
Fix NPE when requested service is unknown
2015-12-30 20:55:21 +01:00
fcfdbe71f5 Added tests for service-layer pattern 2015-12-30 20:55:21 +01:00
52c483f1d0 Added tests for servant pattern 2015-12-30 20:46:40 +01:00
c72faeb67e Added tests for resource-acquisition-is-initialization pattern 2015-12-30 20:46:40 +01:00
299d612b9b Added tests for proxy pattern 2015-12-30 20:46:40 +01:00
9d4c3154b1 Added tests for prototype pattern 2015-12-30 20:46:40 +01:00
a3b1265921 Added tests for property pattern 2015-12-30 20:46:40 +01:00
dca68511e8 Added tests for producer-consumer pattern 2015-12-30 20:46:40 +01:00
42a1dc69ca Added tests for private-class-data pattern 2015-12-30 20:46:40 +01:00
47e1cd710c Added tests for poison-pull pattern 2015-12-30 20:46:40 +01:00
b3d1c2b2ed Added tests for generic observer pattern 2015-12-30 20:46:40 +01:00
3e20a2afa8 Added tests for observer pattern 2015-12-30 20:46:39 +01:00
4c938ab8a5 Added tests for object-pool pattern 2015-12-30 20:46:39 +01:00
8f6f171a3f Added tests for null-object pattern 2015-12-30 20:46:39 +01:00
b4dcec45ef Added tests for multiton pattern 2015-12-30 20:46:39 +01:00
dec5ff22fc Update index.md #324 2015-12-30 18:26:32 +00:00
7b323e9cb4 Updated Class Diagram #324 2015-12-30 17:55:42 +00:00
a0af0a1a76 Merge pull request #325 from DevFactory/utility-classes-should-not-have-public-constructors-fix-3
Utility classes should not have public constructors
2015-12-30 19:55:25 +02:00
7c6e1fc3d8 Merge pull request #323 from DevFactory/code-quality-fix-5
Code quality fixes
2015-12-30 19:47:19 +02:00
45cecf68c4 Updated Class Diagram #324 2015-12-30 17:34:50 +00:00
d7580f5530 Review Comments #324 2015-12-30 16:56:47 +00:00
58b8a06561 Merge branch 'master' of https://github.com/iluwatar/java-design-patterns
* 'master' of https://github.com/iluwatar/java-design-patterns:
  Define checkstyle suppression filter location in maven plugin configuration
2015-12-30 16:17:07 +00:00
befe509582 Define checkstyle suppression filter location in maven plugin configuration 2015-12-30 17:58:03 +02:00
17b889c31d Update to match checkStyle rules added for test packages #324 2015-12-29 22:07:52 +00:00
52192de909 Merge commit '8b020837eaacc9ed4497f3c2461984935314bfb8' into add-delegation-pattern
* commit '8b020837eaacc9ed4497f3c2461984935314bfb8':
  Checkstyle corrections
  Checkstyle configuration to look into test classes too
  Rephrase readme title
  Corrected difficulty for Visitor #213
  Add performance tag to relevant patterns #213
  Categorize and tag all patterns #213
  Update CONTRIBUTING.MD
  Update CONTRIBUTING.MD
  add-contributing
2015-12-29 22:00:56 +00:00
8b020837ea Checkstyle corrections 2015-12-29 21:34:27 +02:00
b369812511 Checkstyle configuration to look into test classes too 2015-12-29 13:27:49 +02:00
52d6e20ad9 Readd File to Index#324 2015-12-28 22:13:05 +00:00
749880e3b9 Messed up indexes #324 2015-12-28 22:12:11 +00:00
41593774c6 CheckStyle reporting strange error about classname, suspect caching, forcing a clean build #324 2015-12-28 21:56:41 +00:00
0bc722f797 Fix CheckStyle #324 2015-12-28 20:34:28 +00:00
fcadb223ce Merge branch 'add-delegation-pattern'
* add-delegation-pattern:
  Add java documentation #324
  Populate the index.md for the delegate module #324
  Move App.java to correct Package #324
  Move App.java to correct Package #324
  Generic For AbstractPrinterController #324
  Generate UML for delegation pattern
  Add simple tests for delegate pattern #324
  Make AppTest.java match other patterns and update AppTest.java to match other patterns #324
  3am Code is starting to show. Get this build working. #324
  Created a unit test for build, added junit to pom for delegation maven module. #324
  Add template index.md for population later #324
  Added skeleton code for delegation pattern #324
  Create maven module for delegation pattern #324
2015-12-28 20:01:14 +00:00
c842f88eb7 Add java documentation #324 2015-12-28 19:23:00 +00:00
6d516d5124 Populate the index.md for the delegate module #324 2015-12-28 18:16:58 +00:00
9544dd321a Rephrase readme title 2015-12-28 20:09:53 +02:00
d623e9c8fd Corrected difficulty for Visitor #213 2015-12-28 19:52:10 +02:00
e27de33f75 Add performance tag to relevant patterns #213 2015-12-28 16:07:43 +02:00
7ac7e3b097 Categorize and tag all patterns #213 2015-12-28 15:52:44 +02:00
fefb51c46e Merge pull request #329 from zafarella/patch-1
add-contributing
2015-12-28 09:34:14 +02:00
58547fae8f Update CONTRIBUTING.MD
real fix :)
2015-12-27 22:44:15 -05:00
30676f8d4f Update CONTRIBUTING.MD
fix the typo
2015-12-27 22:42:42 -05:00
483db04cef Move App.java to correct Package #324 2015-12-27 20:12:04 +00:00
fac10dc454 Move App.java to correct Package #324 2015-12-27 20:10:48 +00:00
982f9f5e31 Generic For AbstractPrinterController #324 2015-12-27 20:09:33 +00:00
74d1823078 Merge pull request #1 from fluxw42/add-delegation-pattern
Generate UML for delegation pattern
2015-12-27 20:03:42 +00:00
f59f18091e Remove Coverity scan #327 2015-12-27 21:23:09 +02:00
5f033be54f Fix PMD violations #327 2015-12-27 21:21:57 +02:00
df911baf36 Added maven pmd plugin and configured it to fail build when violations are found #327 2015-12-27 21:21:31 +02:00
32e7181478 Generate UML for delegation pattern 2015-12-27 18:13:34 +01:00
c8a750df49 Fixing squid:S1118 - Utility classes should not have public constructors 2015-12-27 21:17:13 +05:00
191078735f Fixing squid:S1698 - Objects should be compared with equals() and squid:HiddenFieldCheck - Local variables should not shadow class fields 2015-12-27 21:12:35 +05:00
fa6a6006c3 add-contributing
so github will show link whenever PR are made
2015-12-27 11:03:21 -05:00
a49dbefb56 Add simple tests for delegate pattern #324 2015-12-27 14:10:49 +00:00
fb0617e9c5 Make AppTest.java match other patterns and update AppTest.java to match other patterns #324 2015-12-27 13:59:50 +00:00
84fd2348ea 3am Code is starting to show. Get this build working. #324 2015-12-26 23:02:45 +00:00
f0ff8ad4b3 Created a unit test for build, added junit to pom for delegation maven module. #324 2015-12-26 22:55:12 +00:00
c3184255bf Add template index.md for population later #324 2015-12-26 22:29:45 +00:00
bdacfe30c1 Added skeleton code for delegation pattern #324 2015-12-26 22:20:53 +00:00
30363cbb7f Create maven module for delegation pattern #324 2015-12-26 22:05:12 +00:00
3d8c64d76d Merge pull request #322 from DevFactory/dead-stores-fix-1
Fixing squid:S1854 - Dead stores should be removed
2015-12-26 13:38:16 +02:00
78fcd63271 Merge branch 'fluxw42-master' 2015-12-26 13:07:37 +02:00
30bc25b5bf Merge branch 'master' of https://github.com/fluxw42/java-design-patterns into fluxw42-master
Conflicts:
	monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
2015-12-26 12:36:38 +02:00
6b1356a160 Add Gitter link to README.md 2015-12-26 12:12:33 +02:00
cec9a99410 Adjust checkstyle rules. Make checkstyle fail the build when violations are found. Correct all current checkstyle violations. 2015-12-25 23:49:28 +02:00
9fbb085985 Checkstyle fails the build when violations are detected 2015-12-23 13:20:39 +02:00
6e496e7c86 Fixing squid:S1854 - Dead stores should be removed 2015-12-23 13:41:38 +05:00
e3e0e32e92 Fixed failing unit test
LoadBalancer has several static fields, this could cause problems since
JUnit tests are executed concurrently.
2015-12-21 14:35:36 +01:00
531158c836 Added tests for monostate pattern 2015-12-21 13:29:25 +01:00
6fe01e73b2 Add additional tests for model-view-presenter pattern 2015-12-21 12:17:20 +01:00
69c9374669 Added tests for model-view-controller pattern 2015-12-20 14:31:36 +01:00
a57a71b09c Added tests for memento pattern 2015-12-20 10:39:02 +01:00
719f80a0d6 Added tests for mediator pattern 2015-12-20 00:00:07 +01:00
2c82bd9450 Added tests for lazy-loading pattern 2015-12-19 21:44:50 +01:00
5948a82cf2 Added tests for layers pattern 2015-12-19 21:44:50 +01:00
a0151826ad Changed page-index to 1 for a better structured navbar 2015-12-19 17:35:49 +01:00
33fe90d177 Merge pull request #317 from fluxw42/master
Added some more JUnit tests
2015-12-15 18:48:31 +02:00
25cacdbbc9 Added tests for iterator pattern 2015-12-14 15:14:48 +01:00
323e4c8751 Added tests for interpreter pattern 2015-12-14 12:46:07 +01:00
de78490d29 Added tests for intercepting-filter pattern 2015-12-13 15:18:13 +01:00
9059d2b96c Added proper tests for front-controller pattern 2015-12-13 13:58:39 +01:00
dbca06a9e7 Added proper tests for half-sync-half-async 2015-12-13 13:04:17 +01:00
ca14e8ddad Add proper tests for flyweight pattern 2015-12-13 11:42:25 +01:00
3dc370e2d1 Add proper tests for flux pattern 2015-12-12 22:43:47 +01:00
4181514c65 Add proper tests for fluent-interface pattern and fixed a little bug 2015-12-12 20:16:10 +01:00
df69a8f986 Add proper tests for execute-around pattern 2015-12-12 20:14:59 +01:00
885d5bb7dd Add proper unit tests for event-aggregator pattern 2015-12-12 20:13:25 +01:00
1b74e0ff67 Merge pull request #316 from fluxw42/master
Added more JUnit tests
2015-12-12 09:44:41 +02:00
94f80d1868 Add proper unit tests for composite pattern 2015-12-11 20:24:56 +01:00
c837ffe234 Add proper unit tests for double-dispatch pattern 2015-12-11 20:24:56 +01:00
2edc1898b1 Add proper unit tests for double-checked-locking pattern 2015-12-11 20:24:56 +01:00
29fc56002a Add proper unit tests for dependency-injection pattern 2015-12-11 20:24:56 +01:00
0643289c74 Dependency org.mockito:mockito-core should have scope 'test' 2015-12-11 20:24:56 +01:00
2c0a5e8703 Add proper unit tests for facade pattern 2015-12-11 20:24:56 +01:00
a3372febd0 Merge pull request #315 from Deses/master
Just  Just a quick fix for the Front-controller pattern.
2015-12-11 20:46:18 +02:00
7df65adbfc Just Just a quick fix for the Front-controller pattern. 2015-12-11 13:54:32 +01:00
d7dd8d42af Merge pull request #312 from fluxw42/master
Add proper unit tests for chain, bridge and builder pattern #293
2015-12-09 20:23:51 +02:00
4e7a8fdaca Merge pull request #314 from iluwatar/fstrategy
Functional approach to Strategy pattern #310
2015-12-08 23:27:01 +02:00
6e59d9554f Functional approach to Strategy pattern #310 2015-12-08 23:25:05 +02:00
e85308fbc4 Merge pull request #309 from JuhoKang/adapterdev
Attempt to solve issue #292
2015-12-08 20:53:15 +02:00
10a94cc91c Add proper unit tests for decorator pattern 2015-12-07 20:37:27 +01:00
e2d8079b36 Fixed code to follow coding conventions 2015-12-07 10:35:32 +09:00
8367c83aca Add proper unit tests for bridge pattern #293 2015-12-06 23:48:48 +01:00
875e5b872c Add proper unit tests for builder pattern #293 2015-12-06 23:14:07 +01:00
1fa617d08d Add proper unit tests for chain pattern #293 2015-12-06 22:58:16 +01:00
6c1f025d0f Apply code formatting rules to async-method-invocation example tests 2015-12-06 21:42:06 +02:00
601964a2d1 Merge pull request #311 from fluxw42/master
Add proper unit tests for async-method-invocation #293
2015-12-06 21:33:03 +02:00
1884df525b Add proper unit tests for async-method-invocation #293 2015-12-06 13:43:01 +01:00
507b89d5e4 Apply project coding conventions to Repository example 2015-12-05 21:26:30 +02:00
02d6754804 Merge pull request #308 from neonds/spring-annotation-config
Annotation Config was added.
2015-12-05 21:12:12 +02:00
e709a196bd Set version number for next development iteration 2015-12-02 23:26:07 +02:00
33b41f872e The new java files was not added.. #292 2015-12-02 18:45:08 +09:00
119d264779 issue #292 2015-12-01 16:00:31 +09:00
9a85dfe9df Annotation Config was added. Now AppConfig contains a Main Method (same logic in App.java) to execute 2015-11-27 21:23:55 -06:00
547 changed files with 11549 additions and 1545 deletions

4
CONTRIBUTING.MD Normal file
View File

@ -0,0 +1,4 @@
This is great you have something to contribute!
Before going any further please read the [wiki](https://github.com/iluwatar/java-design-patterns/wiki)
with conventions and rules we used for this project.

View File

@ -2,11 +2,10 @@
that smart and dearly wants an empty line before a heading to be able to
display it as such, e.g. website) -->
# Design pattern samples in Java
# Design patterns implemented in Java
[![Build status](https://travis-ci.org/iluwatar/java-design-patterns.svg?branch=master)](https://travis-ci.org/iluwatar/java-design-patterns)
[![Coverage Status](https://coveralls.io/repos/iluwatar/java-design-patterns/badge.svg?branch=master)](https://coveralls.io/r/iluwatar/java-design-patterns?branch=master)
[![Coverity Scan Build Status](https://scan.coverity.com/projects/5634/badge.svg)](https://scan.coverity.com/projects/5634)
[![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)
# Introduction
@ -40,7 +39,7 @@ patterns by any of the following approaches
# How to contribute
If you are willing to contribute to the project you will find the relevant information in our [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki).
If you are willing to contribute to the project you will find the relevant information in our [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki). We will help you and answer your questions in the [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns).
# Credits

View File

@ -7,6 +7,7 @@ categories: Creational
tags:
- Java
- Gang Of Four
- Difficulty-Intermediate
---
**Also known as:** Kit

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
<version>1.9.0</version>
</parent>
<artifactId>abstract-factory</artifactId>
<dependencies>

View File

@ -1,20 +1,18 @@
package com.iluwatar.abstractfactory;
/**
*
* The Abstract Factory pattern provides a way to encapsulate a group of individual factories that
* have a common theme without specifying their concrete classes. In normal usage, the client
* software creates a concrete implementation of the abstract factory and then uses the generic
* interface of the factory to create the concrete objects that are part of the theme. The client
* does not know (or care) which concrete objects it gets from each of these internal factories,
* since it uses only the generic interfaces of their products. This pattern separates the details
* of implementation of a set of objects from their general usage and relies on object composition,
* as object creation is implemented in methods exposed in the factory interface.
* The Abstract Factory pattern provides a way to encapsulate a group of individual factories that have a common theme
* without specifying their concrete classes. In normal usage, the client software creates a concrete implementation of
* the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part
* of the theme. The client does not know (or care) which concrete objects it gets from each of these internal
* factories, since it uses only the generic interfaces of their products. This pattern separates the details of
* implementation of a set of objects from their general usage and relies on object composition, as object creation is
* implemented in methods exposed in the factory interface.
* <p>
* The essence of the Abstract Factory pattern is a factory interface ({@link KingdomFactory}) and
* its implementations ({@link ElfKingdomFactory}, {@link OrcKingdomFactory}). The example uses both
* concrete implementations to create a king, a castle and an army.
* The essence of the Abstract Factory pattern is a factory interface ({@link KingdomFactory}) and its implementations (
* {@link ElfKingdomFactory}, {@link OrcKingdomFactory}). The example uses both concrete implementations to create a
* king, a castle and an army.
*
*/
public class App {
@ -23,11 +21,8 @@ public class App {
private Castle castle;
private Army army;
/**
* Creates kingdom
*
* @param factory
*/
public void createKingdom(final KingdomFactory factory) {
setKing(factory.createKing());
@ -47,14 +42,6 @@ public class App {
return factory.createKing();
}
Castle getCastle(final KingdomFactory factory) {
return factory.createCastle();
}
Army getArmy(final KingdomFactory factory) {
return factory.createArmy();
}
public King getKing() {
return king;
}
@ -62,6 +49,10 @@ public class App {
private void setKing(final King king) {
this.king = king;
}
Castle getCastle(final KingdomFactory factory) {
return factory.createCastle();
}
public Castle getCastle() {
return castle;
@ -70,6 +61,10 @@ public class App {
private void setCastle(final Castle castle) {
this.castle = castle;
}
Army getArmy(final KingdomFactory factory) {
return factory.createArmy();
}
public Army getArmy() {
return army;
@ -79,32 +74,32 @@ public class App {
this.army = army;
}
/**
* Program entry point
*
* @param args command line args
* @param args
* command line args
*/
public static void main(String[] args) {
App app = new App();
System.out.println("Elf Kingdom");
KingdomFactory elfKingdomFactory;
elfKingdomFactory = app.getElfKingdomFactory();
app.createKingdom(elfKingdomFactory);
System.out.println(app.getArmy().getDescription());
System.out.println(app.getCastle().getDescription());
System.out.println(app.getKing().getDescription());
System.out.println("\nOrc Kingdom");
KingdomFactory orcKingdomFactory;
orcKingdomFactory = app.getOrcKingdomFactory();
app.createKingdom(orcKingdomFactory);
System.out.println(app.getArmy().getDescription());
System.out.println(app.getCastle().getDescription());
System.out.println(app.getKing().getDescription());
App app = new App();
System.out.println("Elf Kingdom");
KingdomFactory elfKingdomFactory;
elfKingdomFactory = app.getElfKingdomFactory();
app.createKingdom(elfKingdomFactory);
System.out.println(app.getArmy().getDescription());
System.out.println(app.getCastle().getDescription());
System.out.println(app.getKing().getDescription());
System.out.println("\nOrc Kingdom");
KingdomFactory orcKingdomFactory;
orcKingdomFactory = app.getOrcKingdomFactory();
app.createKingdom(orcKingdomFactory);
System.out.println(app.getArmy().getDescription());
System.out.println(app.getCastle().getDescription());
System.out.println(app.getKing().getDescription());
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -1,61 +1,61 @@
<?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
realizations="true" associations="true" dependencies="false" nesting-relationships="true">
<class id="1" language="java" name="com.iluwatar.adapter.GnomeEngineeringManager" project="adapter"
file="/adapter/src/main/java/com/iluwatar/adapter/GnomeEngineeringManager.java" binary="false" corner="BOTTOM_RIGHT">
<position height="106" width="224" x="110" y="210"/>
<class-diagram version="1.1.9" 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.adapter.FishingBoat" project="adapter"
file="/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="656" y="355"/>
<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="2" language="java" name="com.iluwatar.adapter.Engineer" project="adapter"
file="/adapter/src/main/java/com/iluwatar/adapter/Engineer.java" binary="false" corner="BOTTOM_RIGHT">
<position height="88" width="141" x="110" y="356"/>
<class id="2" language="java" name="com.iluwatar.adapter.Captain" project="adapter"
file="/adapter/src/main/java/com/iluwatar/adapter/Captain.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="228" y="185"/>
<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.adapter.BattleFishingBoat" project="adapter"
file="/adapter/src/main/java/com/iluwatar/adapter/BattleFishingBoat.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="463" y="357"/>
<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="4" language="java" name="com.iluwatar.adapter.BattleShip" project="adapter"
file="/adapter/src/main/java/com/iluwatar/adapter/BattleShip.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="466" y="170"/>
<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.adapter.GnomeEngineer" project="adapter"
file="/adapter/src/main/java/com/iluwatar/adapter/GnomeEngineer.java" binary="false" corner="BOTTOM_RIGHT">
<position height="106" width="141" x="374" y="210"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="4" language="java" name="com.iluwatar.adapter.GoblinGlider" project="adapter"
file="/adapter/src/main/java/com/iluwatar/adapter/GoblinGlider.java" binary="false" corner="BOTTOM_RIGHT">
<position height="142" width="130" x="374" y="356"/>
<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="5">
<end type="SOURCE" refId="1"/>
<end type="TARGET" refId="2"/>
<end type="SOURCE" refId="2"/>
<end type="TARGET" refId="4"/>
</realization>
<realization id="6">
<end type="SOURCE" refId="3"/>
<end type="TARGET" refId="2"/>
</realization>
<association id="7">
<end type="SOURCE" refId="1" navigable="false">
<attribute id="8" name="engineer"/>
<multiplicity id="9" minimum="0" maximum="1"/>
<association id="6">
<end type="SOURCE" refId="3" navigable="false">
<attribute id="7" name="boat"/>
<multiplicity id="8" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="2" navigable="true"/>
<end type="TARGET" refId="1" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<realization id="9">
<end type="SOURCE" refId="3"/>
<end type="TARGET" refId="4"/>
</realization>
<association id="10">
<end type="SOURCE" refId="3" navigable="false">
<attribute id="11" name="glider"/>
<end type="SOURCE" refId="2" navigable="false">
<attribute id="11" name="battleship"/>
<multiplicity id="12" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="4" navigable="true"/>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

View File

@ -7,6 +7,7 @@ categories: Structural
tags:
- Java
- Gang Of Four
- Difficulty-Beginner
---
**Also known as:** Wrapper
@ -15,7 +16,7 @@ tags:
expect. Adapter lets classes work together that couldn't otherwise because of
incompatible interfaces.
![alt text](./etc/adapter_1.png "Adapter")
![alt text](./etc/adapter.png "Adapter")
**Applicability:** Use the Adapter pattern when

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
<version>1.9.0</version>
</parent>
<artifactId>adapter</artifactId>
<dependencies>

View File

@ -5,14 +5,23 @@ package com.iluwatar.adapter;
* for an adapter. Interfaces may be incompatible but the inner functionality should suit the need.
* The Adapter design pattern allows otherwise incompatible classes to work together by converting
* the interface of one class into an interface expected by the clients.
*
* <p>There are two variations of the Adapter pattern: The class adapter implements the adaptee's
*
* <p>
* There are two variations of the Adapter pattern: The class adapter implements the adaptee's
* interface whereas the object adapter uses composition to contain the adaptee in the adapter
* object. This example uses the object adapter approach.
*
* <p>The Adapter ({@link GnomeEngineer}) converts the interface of the target class (
* {@link GoblinGlider}) into a suitable one expected by the client ({@link GnomeEngineeringManager}
* ).
*
* <p>
* The Adapter ({@link BattleFishingBoat}) converts the interface of the adaptee class (
* {@link FishingBoat}) into a suitable one expected by the client ( {@link BattleShip} ).
*
* <p>
* The story of this implementation is this. <br>
* Pirates are coming! we need a {@link BattleShip} to fight! We have a {@link FishingBoat} and our
* captain. We have no time to make up a new ship! we need to reuse this {@link FishingBoat}. The
* captain needs a battleship which can fire and move. The spec is in {@link BattleShip}. We will
* use the Adapter pattern to reuse {@link FishingBoat}.
*
*/
public class App {
@ -22,7 +31,8 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
Engineer manager = new GnomeEngineeringManager(new GnomeEngineer());
manager.operateDevice();
Captain captain = new Captain(new BattleFishingBoat());
captain.move();
captain.fire();
}
}

View File

@ -0,0 +1,29 @@
package com.iluwatar.adapter;
/**
*
* Adapter class. Adapts the interface of the device ({@link FishingBoat}) into {@link BattleShip}
* interface expected by the client ({@link Captain}). <br>
* In this case we added a new function fire to suit the interface. We are reusing the
* {@link FishingBoat} without changing itself. The Adapter class can just map the functions of the
* Adaptee or add, delete features of the Adaptee.
*
*/
public class BattleFishingBoat implements BattleShip {
private FishingBoat boat;
public BattleFishingBoat() {
boat = new FishingBoat();
}
@Override
public void fire() {
System.out.println("fire!");
}
@Override
public void move() {
boat.sail();
}
}

View File

@ -0,0 +1,14 @@
package com.iluwatar.adapter;
/**
* The interface expected by the client.<br>
* A Battleship can fire and move.
*
*/
public interface BattleShip {
void fire();
void move();
}

View File

@ -0,0 +1,33 @@
package com.iluwatar.adapter;
/**
* The Captain uses {@link BattleShip} to fight. <br>
* This is the client in the pattern.
*/
public class Captain implements BattleShip {
private BattleShip battleship;
public Captain() {
}
public Captain(BattleShip battleship) {
this.battleship = battleship;
}
public void setBattleship(BattleShip battleship) {
this.battleship = battleship;
}
@Override
public void fire() {
battleship.fire();
}
@Override
public void move() {
battleship.move();
}
}

View File

@ -1,11 +0,0 @@
package com.iluwatar.adapter;
/**
*
* Engineers can operate devices.
*
*/
public interface Engineer {
void operateDevice();
}

View File

@ -0,0 +1,18 @@
package com.iluwatar.adapter;
/**
*
* Device class (adaptee in the pattern). We want to reuse this class
*
*/
public class FishingBoat {
public void sail() {
System.out.println("The Boat is moving to that place");
}
public void fish() {
System.out.println("fishing ...");
}
}

View File

@ -1,23 +0,0 @@
package com.iluwatar.adapter;
/**
*
* Adapter class. Adapts the interface of the device ({@link GoblinGlider}) into {@link Engineer}
* interface expected by the client ({@link GnomeEngineeringManager}).
*
*/
public class GnomeEngineer implements Engineer {
private GoblinGlider glider;
public GnomeEngineer() {
glider = new GoblinGlider();
}
@Override
public void operateDevice() {
glider.attachGlider();
glider.gainSpeed();
glider.takeOff();
}
}

View File

@ -1,26 +0,0 @@
package com.iluwatar.adapter;
/**
* GnomeEngineering manager uses {@link Engineer} to operate devices.
*/
public class GnomeEngineeringManager implements Engineer {
private Engineer engineer;
public GnomeEngineeringManager() {
}
public GnomeEngineeringManager(Engineer engineer) {
this.engineer = engineer;
}
@Override
public void operateDevice() {
engineer.operateDevice();
}
public void setEngineer(Engineer engineer) {
this.engineer = engineer;
}
}

View File

@ -1,21 +0,0 @@
package com.iluwatar.adapter;
/**
*
* Device class (adaptee in the pattern).
*
*/
public class GoblinGlider {
public void attachGlider() {
System.out.println("Glider attached.");
}
public void gainSpeed() {
System.out.println("Gaining speed.");
}
public void takeOff() {
System.out.println("Lift-off!");
}
}

View File

@ -1,37 +1,25 @@
package com.iluwatar.adapter;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/**
* An adapter helps two incompatible interfaces to work together. This is the real world definition
* for an adapter. Interfaces may be incompatible but the inner functionality should suit the need.
* The Adapter design pattern allows otherwise incompatible classes to work together by converting
* the interface of one class into an interface expected by the clients.
* Test class
*
* <p>There are two variations of the Adapter pattern:
* The class adapter implements the adaptee's
* interface whereas the object adapter uses composition to contain the adaptee in the adapter
* object. This example uses the object adapter approach.
*
* <p>The Adapter ({@link GnomeEngineer}) converts the interface
* of the target class ({@link GoblinGlider}) into a suitable one expected by
* the client ({@link GnomeEngineeringManager}
* ).
*/
public class AdapterPatternTest {
private Map<String, Object> beans;
private static final String ENGINEER_BEAN = "engineer";
private static final String BATTLESHIP_BEAN = "engineer";
private static final String MANAGER_BEAN = "manager";
private static final String CAPTAIN_BEAN = "captain";
/**
* This method runs before the test execution and sets the bean objects in the beans Map.
@ -40,29 +28,34 @@ public class AdapterPatternTest {
public void setup() {
beans = new HashMap<>();
GnomeEngineer gnomeEngineer = spy(new GnomeEngineer());
beans.put(ENGINEER_BEAN, gnomeEngineer);
BattleFishingBoat battleFishingBoat = spy(new BattleFishingBoat());
beans.put(BATTLESHIP_BEAN, battleFishingBoat);
GnomeEngineeringManager manager = new GnomeEngineeringManager();
manager.setEngineer((GnomeEngineer) beans.get(ENGINEER_BEAN));
beans.put(MANAGER_BEAN, manager);
Captain captain = new Captain();
captain.setBattleship((BattleFishingBoat) beans.get(BATTLESHIP_BEAN));
beans.put(CAPTAIN_BEAN, captain);
}
/**
* This test asserts that when we call operateDevice() method on a manager bean, it is internally
* calling operateDevice method on the engineer object. The Adapter ({@link GnomeEngineer})
* converts the interface of the target class ( {@link GoblinGlider}) into a suitable one expected
* by the client ({@link GnomeEngineeringManager} ).
* This test asserts that when we use the move() method on a captain bean(client), it is
* internally calling move method on the battleship object. The Adapter ({@link BattleFishingBoat}
* ) converts the interface of the target class ( {@link FishingBoat}) into a suitable one
* expected by the client ({@link Captain} ).
*/
@Test
public void testAdapter() {
Engineer manager = (Engineer) beans.get(MANAGER_BEAN);
BattleShip captain = (BattleShip) beans.get(CAPTAIN_BEAN);
// when manager is asked to operate device
manager.operateDevice();
// when captain moves
captain.move();
// the captain internally calls the battleship object to move
BattleShip battleship = (BattleShip) beans.get(BATTLESHIP_BEAN);
verify(battleship).move();
// same with above with firing
captain.fire();
verify(battleship).fire();
// Manager internally calls the engineer object to operateDevice
Engineer engineer = (Engineer) beans.get(ENGINEER_BEAN);
verify(engineer).operateDevice();
}
}

View File

@ -4,7 +4,10 @@ title: Async Method Invocation
folder: async-method-invocation
permalink: /patterns/async-method-invocation/
categories: Concurrency
tags: Java
tags:
- Java
- Difficulty-Intermediate
- Functional
---
**Intent:** Asynchronous method invocation is pattern where the calling thread

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
<version>1.9.0</version>
</parent>
<artifactId>async-method-invocation</artifactId>
<dependencies>
@ -14,5 +14,10 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -4,24 +4,23 @@ import java.util.concurrent.Callable;
/**
* This application demonstrates the async method invocation pattern. Key parts of the pattern are
* <code>AsyncResult</code> which is an intermediate container for an asynchronously evaluated
* value, <code>AsyncCallback</code> which can be provided to be executed on task completion and
* <code>AsyncExecutor</code> that manages the execution of the async tasks.
* <code>AsyncResult</code> which is an intermediate container for an asynchronously evaluated value,
* <code>AsyncCallback</code> which can be provided to be executed on task completion and <code>AsyncExecutor</code>
* that manages the execution of the async tasks.
* <p>
* The main method shows example flow of async invocations. The main thread starts multiple tasks
* with variable durations and then continues its own work. When the main thread has done it's job
* it collects the results of the async tasks. Two of the tasks are handled with callbacks, meaning
* the callbacks are executed immediately when the tasks complete.
* The main method shows example flow of async invocations. The main thread starts multiple tasks with variable
* durations and then continues its own work. When the main thread has done it's job it collects the results of the
* async tasks. Two of the tasks are handled with callbacks, meaning the callbacks are executed immediately when the
* tasks complete.
* <p>
* Noteworthy difference of thread usage between the async results and callbacks is that the async
* results are collected in the main thread but the callbacks are executed within the worker
* threads. This should be noted when working with thread pools.
* Noteworthy difference of thread usage between the async results and callbacks is that the async results are collected
* in the main thread but the callbacks are executed within the worker threads. This should be noted when working with
* thread pools.
* <p>
* Java provides its own implementations of async method invocation pattern. FutureTask,
* CompletableFuture and ExecutorService are the real world implementations of this pattern. But due
* to the nature of parallel programming, the implementations are not trivial. This example does not
* take all possible scenarios into account but rather provides a simple version that helps to
* understand the pattern.
* Java provides its own implementations of async method invocation pattern. FutureTask, CompletableFuture and
* ExecutorService are the real world implementations of this pattern. But due to the nature of parallel programming,
* the implementations are not trivial. This example does not take all possible scenarios into account but rather
* provides a simple version that helps to understand the pattern.
*
* @see AsyncResult
* @see AsyncCallback
@ -33,6 +32,9 @@ import java.util.concurrent.Callable;
*/
public class App {
/**
* Program entry point
*/
public static void main(String[] args) throws Exception {
// construct a new executor that will run async tasks
AsyncExecutor executor = new ThreadAsyncExecutor();
@ -41,10 +43,8 @@ public class App {
AsyncResult<Integer> asyncResult1 = executor.startProcess(lazyval(10, 500));
AsyncResult<String> asyncResult2 = executor.startProcess(lazyval("test", 300));
AsyncResult<Long> asyncResult3 = executor.startProcess(lazyval(50L, 700));
AsyncResult<Integer> asyncResult4 =
executor.startProcess(lazyval(20, 400), callback("Callback result 4"));
AsyncResult<String> asyncResult5 =
executor.startProcess(lazyval("callback", 600), callback("Callback result 5"));
AsyncResult<Integer> asyncResult4 = executor.startProcess(lazyval(20, 400), callback("Callback result 4"));
AsyncResult<String> asyncResult5 = executor.startProcess(lazyval("callback", 600), callback("Callback result 5"));
// emulate processing in the current thread while async tasks are running in their own threads
Thread.sleep(350); // Oh boy I'm working hard here
@ -66,8 +66,10 @@ public class App {
/**
* Creates a callable that lazily evaluates to given value with artificial delay.
*
* @param value value to evaluate
* @param delayMillis artificial delay in milliseconds
* @param value
* value to evaluate
* @param delayMillis
* artificial delay in milliseconds
* @return new callable for lazy evaluation
*/
private static <T> Callable<T> lazyval(T value, long delayMillis) {
@ -81,7 +83,8 @@ public class App {
/**
* Creates a simple callback that logs the complete status of the async result.
*
* @param name callback name
* @param name
* callback name
* @return new async callback
*/
private static <T> AsyncCallback<T> callback(String name) {

View File

@ -5,8 +5,6 @@ import java.util.concurrent.ExecutionException;
/**
*
* AsyncResult interface
*
* @param <T>
*/
public interface AsyncResult<T> {

View File

@ -29,13 +29,12 @@ public class ThreadAsyncExecutor implements AsyncExecutor {
} catch (Exception ex) {
result.setException(ex);
}
}, "executor-" + idx.incrementAndGet()).start();
} , "executor-" + idx.incrementAndGet()).start();
return result;
}
@Override
public <T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException,
InterruptedException {
public <T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException, InterruptedException {
if (asyncResult.isCompleted()) {
return asyncResult.getValue();
} else {
@ -45,9 +44,8 @@ public class ThreadAsyncExecutor implements AsyncExecutor {
}
/**
* Simple implementation of async result that allows completing it successfully with a value or
* exceptionally with an exception. A really simplified version from its real life cousins
* FutureTask and CompletableFuture.
* Simple implementation of async result that allows completing it successfully with a value or exceptionally with an
* exception. A really simplified version from its real life cousins FutureTask and CompletableFuture.
*
* @see java.util.concurrent.FutureTask
* @see java.util.concurrent.CompletableFuture
@ -71,10 +69,11 @@ public class ThreadAsyncExecutor implements AsyncExecutor {
}
/**
* Sets the value from successful execution and executes callback if available. Notifies any
* thread waiting for completion.
* Sets the value from successful execution and executes callback if available. Notifies any thread waiting for
* completion.
*
* @param value value of the evaluated task
* @param value
* value of the evaluated task
*/
void setValue(T value) {
this.value = value;
@ -86,10 +85,11 @@ public class ThreadAsyncExecutor implements AsyncExecutor {
}
/**
* Sets the exception from failed execution and executes callback if available. Notifies any
* thread waiting for completion.
* Sets the exception from failed execution and executes callback if available. Notifies any thread waiting for
* completion.
*
* @param exception exception of the failed task
* @param exception
* exception of the failed task
*/
void setException(Exception exception) {
this.exception = exception;
@ -102,7 +102,7 @@ public class ThreadAsyncExecutor implements AsyncExecutor {
@Override
public boolean isCompleted() {
return (state > RUNNING);
return state > RUNNING;
}
@Override

View File

@ -0,0 +1,290 @@
package com.iluwatar.async.method.invocation;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import static org.junit.Assert.*;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static org.mockito.internal.verification.VerificationModeFactory.times;
/**
* Date: 12/6/15 - 10:49 AM
*
* @author Jeroen Meulemeester
*/
public class ThreadAsyncExecutorTest {
/**
* Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)}
*/
@Test(timeout = 3000)
public void testSuccessfulTaskWithoutCallback() throws Exception {
// 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 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();
// ... 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)
public void testSuccessfulTaskWithCallback() throws Exception {
// 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 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();
// ... 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());
// ... 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)
public void testLongRunningTaskWithoutCallback() throws Exception {
// 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 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)
public void testLongRunningTaskWithCallback() throws Exception {
// 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 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)
public void testEndProcess() throws Exception {
// 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 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)
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);
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());
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());
}
}
/**
* 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)
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);
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());
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 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());
}
}
/**
* 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)
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);
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());
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

@ -7,6 +7,7 @@ categories: Structural
tags:
- Java
- Gang Of Four
- Difficulty-Intermediate
---
**Also known as:** Handle/Body

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
<version>1.9.0</version>
</parent>
<artifactId>bridge</artifactId>
<dependencies>
@ -14,5 +14,10 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -2,8 +2,6 @@ package com.iluwatar.bridge;
import org.junit.Test;
import com.iluwatar.bridge.App;
/**
*
* Application test

View File

@ -0,0 +1,33 @@
package com.iluwatar.bridge;
import org.junit.Test;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.internal.verification.VerificationModeFactory.times;
/**
* Date: 12/6/15 - 11:15 PM
*
* @author Jeroen Meulemeester
*/
public class BlindingMagicWeaponTest extends MagicWeaponTest {
/**
* Invoke all possible actions on the weapon and check if the actions are executed on the actual
* underlying weapon implementation.
*/
@Test
public void testExcalibur() throws Exception {
final Excalibur excalibur = spy(new Excalibur());
final BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(excalibur);
testBasicWeaponActions(blindingMagicWeapon, excalibur);
blindingMagicWeapon.blind();
verify(excalibur, times(1)).blindImp();
verifyNoMoreInteractions(excalibur);
}
}

View File

@ -0,0 +1,33 @@
package com.iluwatar.bridge;
import org.junit.Test;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.internal.verification.VerificationModeFactory.times;
/**
* Date: 12/6/15 - 11:26 PM
*
* @author Jeroen Meulemeester
*/
public class FlyingMagicWeaponTest extends MagicWeaponTest {
/**
* Invoke all possible actions on the weapon and check if the actions are executed on the actual
* underlying weapon implementation.
*/
@Test
public void testMjollnir() throws Exception {
final Mjollnir mjollnir = spy(new Mjollnir());
final FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(mjollnir);
testBasicWeaponActions(flyingMagicWeapon, mjollnir);
flyingMagicWeapon.fly();
verify(mjollnir, times(1)).flyImp();
verifyNoMoreInteractions(mjollnir);
}
}

View File

@ -0,0 +1,42 @@
package com.iluwatar.bridge;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.internal.verification.VerificationModeFactory.times;
/**
* Date: 12/6/15 - 11:28 PM
*
* @author Jeroen Meulemeester
*/
public abstract class MagicWeaponTest {
/**
* Invoke the basic actions of the given weapon, and test if the underlying weapon implementation
* is invoked
*
* @param weaponImpl The spied weapon implementation where actions are bridged to
* @param weapon The weapon, handled by the app
*/
protected final void testBasicWeaponActions(final MagicWeapon weapon,
final MagicWeaponImpl weaponImpl) {
assertNotNull(weapon);
assertNotNull(weaponImpl);
assertNotNull(weapon.getImp());
weapon.swing();
verify(weaponImpl, times(1)).swingImp();
verifyNoMoreInteractions(weaponImpl);
weapon.wield();
verify(weaponImpl, times(1)).wieldImp();
verifyNoMoreInteractions(weaponImpl);
weapon.unwield();
verify(weaponImpl, times(1)).unwieldImp();
verifyNoMoreInteractions(weaponImpl);
}
}

View File

@ -0,0 +1,33 @@
package com.iluwatar.bridge;
import org.junit.Test;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.internal.verification.VerificationModeFactory.times;
/**
* Date: 12/6/15 - 11:43 PM
*
* @author Jeroen Meulemeester
*/
public class SoulEatingMagicWeaponTest extends MagicWeaponTest {
/**
* Invoke all possible actions on the weapon and check if the actions are executed on the actual
* underlying weapon implementation.
*/
@Test
public void testStormBringer() throws Exception {
final Stormbringer stormbringer = spy(new Stormbringer());
final SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(stormbringer);
testBasicWeaponActions(soulEatingMagicWeapon, stormbringer);
soulEatingMagicWeapon.eatSoul();
verify(stormbringer, times(1)).eatSoulImp();
verifyNoMoreInteractions(stormbringer);
}
}

View File

@ -7,6 +7,7 @@ categories: Creational
tags:
- Java
- Gang Of Four
- Difficulty-Intermediate
---
**Intent:** Separate the construction of a complex object from its

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
<version>1.9.0</version>
</parent>
<artifactId>builder</artifactId>
<dependencies>

View File

@ -93,6 +93,9 @@ public class Hero {
private Armor armor;
private Weapon weapon;
/**
* Constructor
*/
public HeroBuilder(Profession profession, String name) {
if (profession == null || name == null) {
throw new IllegalArgumentException("profession and name can not be null");

View File

@ -2,8 +2,6 @@ package com.iluwatar.builder;
import org.junit.Test;
import com.iluwatar.builder.App;
/**
*
* Application test

View File

@ -0,0 +1,56 @@
package com.iluwatar.builder;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Date: 12/6/15 - 11:01 PM
*
* @author Jeroen Meulemeester
*/
public class HeroTest {
/**
* Test if we get the expected exception when trying to create a hero without a profession
*/
@Test(expected = IllegalArgumentException.class)
public void testMissingProfession() throws Exception {
new Hero.HeroBuilder(null, "Sir without a job");
}
/**
* Test if we get the expected exception when trying to create a hero without a name
*/
@Test(expected = IllegalArgumentException.class)
public void testMissingName() throws Exception {
new Hero.HeroBuilder(Profession.THIEF, null);
}
/**
* Test if the hero build by the builder has the correct attributes, as requested
*/
@Test
public void testBuildHero() throws Exception {
final String heroName = "Sir Lancelot";
final Hero hero = new Hero.HeroBuilder(Profession.WARRIOR, heroName)
.withArmor(Armor.CHAIN_MAIL)
.withWeapon(Weapon.SWORD)
.withHairType(HairType.LONG_CURLY)
.withHairColor(HairColor.BLOND)
.build();
assertNotNull(hero);
assertNotNull(hero.toString());
assertEquals(Profession.WARRIOR, hero.getProfession());
assertEquals(heroName, hero.getName());
assertEquals(Armor.CHAIN_MAIL, hero.getArmor());
assertEquals(Weapon.SWORD, hero.getWeapon());
assertEquals(HairType.LONG_CURLY, hero.getHairType());
assertEquals(HairColor.BLOND, hero.getHairColor());
}
}

View File

@ -4,7 +4,9 @@ title: Business Delegate
folder: business-delegate
permalink: /patterns/business-delegate/
categories: Business Tier
tags: Java
tags:
- Java
- Difficulty-Intermediate
---
**Intent:** The Business Delegate pattern adds an abstraction layer between

View File

@ -6,7 +6,7 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
<version>1.9.0</version>
</parent>
<artifactId>business-delegate</artifactId>
<dependencies>

View File

@ -5,20 +5,20 @@ package com.iluwatar.business.delegate;
*/
public class BusinessDelegate {
private BusinessLookup lookupService;
private BusinessService businessService;
private ServiceType serviceType;
private BusinessLookup lookupService;
private BusinessService businessService;
private ServiceType serviceType;
public void setLookupService(BusinessLookup businessLookup) {
this.lookupService = businessLookup;
}
public void setLookupService(BusinessLookup businessLookup) {
this.lookupService = businessLookup;
}
public void setServiceType(ServiceType serviceType) {
this.serviceType = serviceType;
}
public void setServiceType(ServiceType serviceType) {
this.serviceType = serviceType;
}
public void doTask() {
businessService = lookupService.getBusinessService(serviceType);
businessService.doProcessing();
}
public void doTask() {
businessService = lookupService.getBusinessService(serviceType);
businessService.doProcessing();
}
}

View File

@ -6,6 +6,8 @@ permalink: /patterns/caching/
categories: Other
tags:
- Java
- Difficulty-Intermediate
- Performance
---
**Intent:** To avoid expensive re-acquisition of resources by not releasing

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
<version>1.9.0</version>
</parent>
<artifactId>caching</artifactId>
<dependencies>

View File

@ -21,7 +21,7 @@ package com.iluwatar.caching;
* application data. The cache itself is implemented as an internal (Java) data structure. It adopts
* a Least-Recently-Used (LRU) strategy for evicting data from itself when its full. The three
* strategies are individually tested. The testing of the cache is restricted towards saving and
* querying of user accounts from the underlying data store ( {@link DBManager}). The main class (
* querying of user accounts from the underlying data store ( {@link DbManager}). The main class (
* {@link App} is not aware of the underlying mechanics of the application (i.e. save and query) and
* whether the data is coming from the cache or the DB (i.e. separation of concern). The AppManager
* ({@link AppManager}) handles the transaction of data to-and-from the underlying data store
@ -43,7 +43,7 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
AppManager.initDB(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests
AppManager.initDb(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests
// and the App class to avoid Maven compilation errors. Set flag to
// true to run the tests with MongoDB (provided that MongoDB is
// installed and socket connection is open).
@ -65,8 +65,8 @@ public class App {
AppManager.save(userAccount1);
System.out.println(AppManager.printCacheContent());
userAccount1 = AppManager.find("001");
userAccount1 = AppManager.find("001");
AppManager.find("001");
AppManager.find("001");
}
/**
@ -80,15 +80,15 @@ public class App {
AppManager.save(userAccount2);
System.out.println(AppManager.printCacheContent());
userAccount2 = AppManager.find("002");
AppManager.find("002");
System.out.println(AppManager.printCacheContent());
userAccount2 = AppManager.find("002");
userAccount2.setUserName("Jane G.");
AppManager.save(userAccount2);
System.out.println(AppManager.printCacheContent());
userAccount2 = AppManager.find("002");
AppManager.find("002");
System.out.println(AppManager.printCacheContent());
userAccount2 = AppManager.find("002");
AppManager.find("002");
}
/**
@ -106,12 +106,12 @@ public class App {
AppManager.save(userAccount4);
AppManager.save(userAccount5);
System.out.println(AppManager.printCacheContent());
userAccount3 = AppManager.find("003");
AppManager.find("003");
System.out.println(AppManager.printCacheContent());
UserAccount userAccount6 = new UserAccount("006", "Yasha", "She is an only child.");
AppManager.save(userAccount6);
System.out.println(AppManager.printCacheContent());
userAccount4 = AppManager.find("004");
AppManager.find("004");
System.out.println(AppManager.printCacheContent());
}
}

View File

@ -15,24 +15,30 @@ public class AppManager {
private static CachingPolicy cachingPolicy;
private AppManager() {
}
/**
*
* Developer/Tester is able to choose whether the application should use MongoDB as its underlying
* data storage or a simple Java data structure to (temporarily) store the data/objects during
* runtime.
*/
public static void initDB(boolean useMongoDB) {
if (useMongoDB) {
public static void initDb(boolean useMongoDb) {
if (useMongoDb) {
try {
DBManager.connect();
DbManager.connect();
} catch (ParseException e) {
e.printStackTrace();
}
} else {
DBManager.createVirtualDB();
DbManager.createVirtualDb();
}
}
/**
* Initialize caching policy
*/
public static void initCachingPolicy(CachingPolicy policy) {
cachingPolicy = policy;
if (cachingPolicy == CachingPolicy.BEHIND) {
@ -50,15 +56,21 @@ public class AppManager {
CacheStore.initCapacity(capacity);
}
public static UserAccount find(String userID) {
/**
* Find user account
*/
public static UserAccount find(String userId) {
if (cachingPolicy == CachingPolicy.THROUGH || cachingPolicy == CachingPolicy.AROUND) {
return CacheStore.readThrough(userID);
return CacheStore.readThrough(userId);
} else if (cachingPolicy == CachingPolicy.BEHIND) {
return CacheStore.readThroughWithWriteBackPolicy(userID);
return CacheStore.readThroughWithWriteBackPolicy(userId);
}
return null;
}
/**
* Save user account
*/
public static void save(UserAccount userAccount) {
if (cachingPolicy == CachingPolicy.THROUGH) {
CacheStore.writeThrough(userAccount);

View File

@ -9,73 +9,99 @@ import java.util.ArrayList;
*/
public class CacheStore {
static LRUCache cache = null;
static LruCache cache = null;
public static void initCapacity(int capacity) {
if (null == cache)
cache = new LRUCache(capacity);
else
cache.setCapacity(capacity);
private CacheStore() {
}
public static UserAccount readThrough(String userID) {
if (cache.contains(userID)) {
/**
* Init cache capacity
*/
public static void initCapacity(int capacity) {
if (null == cache) {
cache = new LruCache(capacity);
} else {
cache.setCapacity(capacity);
}
}
/**
* Get user account using read-through cache
*/
public static UserAccount readThrough(String userId) {
if (cache.contains(userId)) {
System.out.println("# Cache Hit!");
return cache.get(userID);
return cache.get(userId);
}
System.out.println("# Cache Miss!");
UserAccount userAccount = DBManager.readFromDB(userID);
cache.set(userID, userAccount);
UserAccount userAccount = DbManager.readFromDb(userId);
cache.set(userId, userAccount);
return userAccount;
}
/**
* Get user account using write-through cache
*/
public static void writeThrough(UserAccount userAccount) {
if (cache.contains(userAccount.getUserID())) {
DBManager.updateDB(userAccount);
if (cache.contains(userAccount.getUserId())) {
DbManager.updateDb(userAccount);
} else {
DBManager.writeToDB(userAccount);
DbManager.writeToDb(userAccount);
}
cache.set(userAccount.getUserID(), userAccount);
cache.set(userAccount.getUserId(), userAccount);
}
/**
* Get user account using write-around cache
*/
public static void writeAround(UserAccount userAccount) {
if (cache.contains(userAccount.getUserID())) {
DBManager.updateDB(userAccount);
cache.invalidate(userAccount.getUserID()); // Cache data has been updated -- remove older
if (cache.contains(userAccount.getUserId())) {
DbManager.updateDb(userAccount);
cache.invalidate(userAccount.getUserId()); // Cache data has been updated -- remove older
// version from cache.
} else {
DBManager.writeToDB(userAccount);
DbManager.writeToDb(userAccount);
}
}
public static UserAccount readThroughWithWriteBackPolicy(String userID) {
if (cache.contains(userID)) {
/**
* Get user account using read-through cache with write-back policy
*/
public static UserAccount readThroughWithWriteBackPolicy(String userId) {
if (cache.contains(userId)) {
System.out.println("# Cache Hit!");
return cache.get(userID);
return cache.get(userId);
}
System.out.println("# Cache Miss!");
UserAccount userAccount = DBManager.readFromDB(userID);
UserAccount userAccount = DbManager.readFromDb(userId);
if (cache.isFull()) {
System.out.println("# Cache is FULL! Writing LRU data to DB...");
UserAccount toBeWrittenToDB = cache.getLRUData();
DBManager.upsertDB(toBeWrittenToDB);
UserAccount toBeWrittenToDb = cache.getLruData();
DbManager.upsertDb(toBeWrittenToDb);
}
cache.set(userID, userAccount);
cache.set(userId, userAccount);
return userAccount;
}
/**
* Set user account
*/
public static void writeBehind(UserAccount userAccount) {
if (cache.isFull() && !cache.contains(userAccount.getUserID())) {
if (cache.isFull() && !cache.contains(userAccount.getUserId())) {
System.out.println("# Cache is FULL! Writing LRU data to DB...");
UserAccount toBeWrittenToDB = cache.getLRUData();
DBManager.upsertDB(toBeWrittenToDB);
UserAccount toBeWrittenToDb = cache.getLruData();
DbManager.upsertDb(toBeWrittenToDb);
}
cache.set(userAccount.getUserID(), userAccount);
cache.set(userAccount.getUserId(), userAccount);
}
/**
* Clears cache
*/
public static void clearCache() {
if (null != cache)
if (null != cache) {
cache.clear();
}
}
/**
@ -83,14 +109,18 @@ public class CacheStore {
*/
public static void flushCache() {
System.out.println("# flushCache...");
if (null == cache)
if (null == cache) {
return;
}
ArrayList<UserAccount> listOfUserAccounts = cache.getCacheDataInListForm();
for (UserAccount userAccount : listOfUserAccounts) {
DBManager.upsertDB(userAccount);
DbManager.upsertDb(userAccount);
}
}
/**
* Print user accounts
*/
public static String print() {
ArrayList<UserAccount> listOfUserAccounts = cache.getCacheDataInListForm();
StringBuilder sb = new StringBuilder();

View File

@ -21,7 +21,7 @@ import com.mongodb.client.model.UpdateOptions;
* during runtime (createVirtualDB()).</p>
*
*/
public class DBManager {
public class DbManager {
private static MongoClient mongoClient;
private static MongoDatabase db;
@ -29,21 +29,34 @@ public class DBManager {
private static HashMap<String, UserAccount> virtualDB;
public static void createVirtualDB() {
private DbManager() {
}
/**
* Create DB
*/
public static void createVirtualDb() {
useMongoDB = false;
virtualDB = new HashMap<String, UserAccount>();
}
/**
* Connect to DB
*/
public static void connect() throws ParseException {
useMongoDB = true;
mongoClient = new MongoClient();
db = mongoClient.getDatabase("test");
}
public static UserAccount readFromDB(String userID) {
/**
* Read user account from DB
*/
public static UserAccount readFromDb(String userId) {
if (!useMongoDB) {
if (virtualDB.containsKey(userID))
return virtualDB.get(userID);
if (virtualDB.containsKey(userId)) {
return virtualDB.get(userId);
}
return null;
}
if (null == db) {
@ -54,18 +67,22 @@ public class DBManager {
}
}
FindIterable<Document> iterable =
db.getCollection("user_accounts").find(new Document("userID", userID));
if (iterable == null)
db.getCollection("user_accounts").find(new Document("userID", userId));
if (iterable == null) {
return null;
}
Document doc = iterable.first();
UserAccount userAccount =
new UserAccount(userID, doc.getString("userName"), doc.getString("additionalInfo"));
new UserAccount(userId, doc.getString("userName"), doc.getString("additionalInfo"));
return userAccount;
}
public static void writeToDB(UserAccount userAccount) {
/**
* Write user account to DB
*/
public static void writeToDb(UserAccount userAccount) {
if (!useMongoDB) {
virtualDB.put(userAccount.getUserID(), userAccount);
virtualDB.put(userAccount.getUserId(), userAccount);
return;
}
if (null == db) {
@ -76,13 +93,16 @@ public class DBManager {
}
}
db.getCollection("user_accounts").insertOne(
new Document("userID", userAccount.getUserID()).append("userName",
new Document("userID", userAccount.getUserId()).append("userName",
userAccount.getUserName()).append("additionalInfo", userAccount.getAdditionalInfo()));
}
public static void updateDB(UserAccount userAccount) {
/**
* Update DB
*/
public static void updateDb(UserAccount userAccount) {
if (!useMongoDB) {
virtualDB.put(userAccount.getUserID(), userAccount);
virtualDB.put(userAccount.getUserId(), userAccount);
return;
}
if (null == db) {
@ -93,7 +113,7 @@ public class DBManager {
}
}
db.getCollection("user_accounts").updateOne(
new Document("userID", userAccount.getUserID()),
new Document("userID", userAccount.getUserId()),
new Document("$set", new Document("userName", userAccount.getUserName()).append(
"additionalInfo", userAccount.getAdditionalInfo())));
}
@ -102,9 +122,9 @@ public class DBManager {
*
* Insert data into DB if it does not exist. Else, update it.
*/
public static void upsertDB(UserAccount userAccount) {
public static void upsertDb(UserAccount userAccount) {
if (!useMongoDB) {
virtualDB.put(userAccount.getUserID(), userAccount);
virtualDB.put(userAccount.getUserId(), userAccount);
return;
}
if (null == db) {
@ -115,8 +135,8 @@ public class DBManager {
}
}
db.getCollection("user_accounts").updateOne(
new Document("userID", userAccount.getUserID()),
new Document("$set", new Document("userID", userAccount.getUserID()).append("userName",
new Document("userID", userAccount.getUserId()),
new Document("$set", new Document("userID", userAccount.getUserId()).append("userName",
userAccount.getUserName()).append("additionalInfo", userAccount.getAdditionalInfo())),
new UpdateOptions().upsert(true));
}

View File

@ -12,16 +12,16 @@ import java.util.HashMap;
* LRU data is always at the end of the list.
*
*/
public class LRUCache {
public class LruCache {
class Node {
String userID;
String userId;
UserAccount userAccount;
Node previous;
Node next;
public Node(String userID, UserAccount userAccount) {
this.userID = userID;
public Node(String userId, UserAccount userAccount) {
this.userId = userId;
this.userAccount = userAccount;
}
}
@ -31,13 +31,16 @@ public class LRUCache {
Node head = null;
Node end = null;
public LRUCache(int capacity) {
public LruCache(int capacity) {
this.capacity = capacity;
}
public UserAccount get(String userID) {
if (cache.containsKey(userID)) {
Node node = cache.get(userID);
/**
* Get user account
*/
public UserAccount get(String userId) {
if (cache.containsKey(userId)) {
Node node = cache.get(userId);
remove(node);
setHead(node);
return node.userAccount;
@ -69,52 +72,63 @@ public class LRUCache {
public void setHead(Node node) {
node.next = head;
node.previous = null;
if (head != null)
if (head != null) {
head.previous = node;
}
head = node;
if (end == null)
if (end == null) {
end = head;
}
}
public void set(String userID, UserAccount userAccount) {
if (cache.containsKey(userID)) {
Node old = cache.get(userID);
/**
* Set user account
*/
public void set(String userId, UserAccount userAccount) {
if (cache.containsKey(userId)) {
Node old = cache.get(userId);
old.userAccount = userAccount;
remove(old);
setHead(old);
} else {
Node newNode = new Node(userID, userAccount);
Node newNode = new Node(userId, userAccount);
if (cache.size() >= capacity) {
System.out.println("# Cache is FULL! Removing " + end.userID + " from cache...");
cache.remove(end.userID); // remove LRU data from cache.
System.out.println("# Cache is FULL! Removing " + end.userId + " from cache...");
cache.remove(end.userId); // remove LRU data from cache.
remove(end);
setHead(newNode);
} else {
setHead(newNode);
}
cache.put(userID, newNode);
cache.put(userId, newNode);
}
}
public boolean contains(String userID) {
return cache.containsKey(userID);
public boolean contains(String userId) {
return cache.containsKey(userId);
}
public void invalidate(String userID) {
System.out.println("# " + userID + " has been updated! Removing older version from cache...");
Node toBeRemoved = cache.get(userID);
/**
* Invalidate cache for user
*/
public void invalidate(String userId) {
System.out.println("# " + userId + " has been updated! Removing older version from cache...");
Node toBeRemoved = cache.get(userId);
remove(toBeRemoved);
cache.remove(userID);
cache.remove(userId);
}
public boolean isFull() {
return cache.size() >= capacity;
}
public UserAccount getLRUData() {
public UserAccount getLruData() {
return end.userAccount;
}
/**
* Clear cache
*/
public void clear() {
head = null;
end = null;
@ -135,6 +149,9 @@ public class LRUCache {
return listOfCacheData;
}
/**
* Set cache capacity
*/
public void setCapacity(int newCapacity) {
if (capacity > newCapacity) {
clear(); // Behavior can be modified to accommodate for decrease in cache size. For now, we'll

View File

@ -6,22 +6,25 @@ package com.iluwatar.caching;
*
*/
public class UserAccount {
private String userID;
private String userId;
private String userName;
private String additionalInfo;
public UserAccount(String userID, String userName, String additionalInfo) {
this.userID = userID;
/**
* Constructor
*/
public UserAccount(String userId, String userName, String additionalInfo) {
this.userId = userId;
this.userName = userName;
this.additionalInfo = additionalInfo;
}
public String getUserID() {
return userID;
public String getUserId() {
return userId;
}
public void setUserID(String userID) {
this.userID = userID;
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
@ -42,6 +45,6 @@ public class UserAccount {
@Override
public String toString() {
return userID + ", " + userName + ", " + additionalInfo;
return userId + ", " + userName + ", " + additionalInfo;
}
}

View File

@ -16,7 +16,7 @@ public class AppTest {
*/
@Before
public void setUp() {
AppManager.initDB(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests
AppManager.initDb(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests
// to avoid Maven compilation errors. Set flag to true to run the
// tests with MongoDB (provided that MongoDB is installed and socket
// connection is open).

View File

@ -4,7 +4,11 @@ title: Callback
folder: callback
permalink: /patterns/callback/
categories: Other
tags: Java
tags:
- Java
- Difficulty-Beginner
- Functional
- Idiom
---
**Intent:** Callback is a piece of executable code that is passed as an

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
<version>1.9.0</version>
</parent>
<artifactId>callback</artifactId>
<dependencies>

View File

@ -9,6 +9,9 @@ package com.iluwatar.callback;
*/
public class App {
/**
* Program entry point
*/
public static void main(String[] args) {
Task task = new SimpleTask();
Callback callback = new Callback() {

View File

@ -7,5 +7,5 @@ package com.iluwatar.callback;
*/
public interface Callback {
public void call();
void call();
}

View File

@ -7,6 +7,9 @@ package com.iluwatar.callback;
*/
public abstract class Task {
/**
* Execute with callback
*/
public final void executeWith(Callback callback) {
execute();
if (callback != null) {

View File

@ -7,6 +7,7 @@ categories: Behavioral
tags:
- Java
- Gang Of Four
- Difficulty-Intermediate
---
**Intent:** Avoid coupling the sender of a request to its receiver by giving

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
<version>1.9.0</version>
</parent>
<artifactId>chain</artifactId>
<dependencies>

View File

@ -15,6 +15,7 @@ public class OrcCommander extends RequestHandler {
public void handleRequest(Request req) {
if (req.getRequestType().equals(RequestType.DEFEND_CASTLE)) {
printHandling(req);
req.markHandled();
} else {
super.handleRequest(req);
}

View File

@ -15,6 +15,7 @@ public class OrcOfficer extends RequestHandler {
public void handleRequest(Request req) {
if (req.getRequestType().equals(RequestType.TORTURE_PRISONER)) {
printHandling(req);
req.markHandled();
} else {
super.handleRequest(req);
}

View File

@ -15,6 +15,7 @@ public class OrcSoldier extends RequestHandler {
public void handleRequest(Request req) {
if (req.getRequestType().equals(RequestType.COLLECT_TAX)) {
printHandling(req);
req.markHandled();
} else {
super.handleRequest(req);
}

View File

@ -1,38 +1,78 @@
package com.iluwatar.chain;
import java.util.Objects;
/**
*
* Request
*
*/
public class Request {
private String requestDescription;
private RequestType requestType;
/**
* The type of this request, used by each item in the chain to see if they should or can handle
* this particular request
*/
private final RequestType requestType;
public Request(RequestType requestType, String requestDescription) {
this.setRequestType(requestType);
this.setRequestDescription(requestDescription);
/**
* A description of the request
*/
private final String requestDescription;
/**
* Indicates if the request is handled or not. A request can only switch state from unhandled to
* handled, there's no way to 'unhandle' a request
*/
private boolean handled = false;
/**
* Create a new request of the given type and accompanied description.
*
* @param requestType The type of request
* @param requestDescription The description of the request
*/
public Request(final RequestType requestType, final String requestDescription) {
this.requestType = Objects.requireNonNull(requestType);
this.requestDescription = Objects.requireNonNull(requestDescription);
}
/**
* Get a description of the request
*
* @return A human readable description of the request
*/
public String getRequestDescription() {
return requestDescription;
}
public void setRequestDescription(String requestDescription) {
this.requestDescription = requestDescription;
}
/**
* Get the type of this request, used by each person in the chain of command to see if they should
* or can handle this particular request
*
* @return The request type
*/
public RequestType getRequestType() {
return requestType;
}
public void setRequestType(RequestType requestType) {
this.requestType = requestType;
/**
* Mark the request as handled
*/
public void markHandled() {
this.handled = true;
}
/**
* Indicates if this request is handled or not
*
* @return <tt>true</tt> when the request is handled, <tt>false</tt> if not
*/
public boolean isHandled() {
return this.handled;
}
@Override
public String toString() {
return getRequestDescription();
}
}

View File

@ -13,6 +13,9 @@ public abstract class RequestHandler {
this.next = next;
}
/**
* Request handler
*/
public void handleRequest(Request req) {
if (next != null) {
next.handleRequest(req);

View File

@ -2,8 +2,6 @@ package com.iluwatar.chain;
import org.junit.Test;
import com.iluwatar.chain.App;
/**
*
* Application test

View File

@ -0,0 +1,37 @@
package com.iluwatar.chain;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* Date: 12/6/15 - 9:29 PM
*
* @author Jeroen Meulemeester
*/
public class OrcKingTest {
/**
* All possible requests
*/
private static final Request[] REQUESTS = new Request[]{
new Request(RequestType.DEFEND_CASTLE, "Don't let the barbarians enter my castle!!"),
new Request(RequestType.TORTURE_PRISONER, "Don't just stand there, tickle him!"),
new Request(RequestType.COLLECT_TAX, "Don't steal, the King hates competition ..."),
};
@Test
public void testMakeRequest() throws Exception {
final OrcKing king = new OrcKing();
for (final Request request : REQUESTS) {
king.makeRequest(request);
assertTrue(
"Expected all requests from King to be handled, but [" + request + "] was not!",
request.isHandled()
);
}
}
}

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suppressions PUBLIC "-//Puppy Crawl//DTD Suppressions 1.1//EN"
"http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
<suppress checks="AvoidStarImport" files="[\\/]src[\\/]test[\\/]java[\\/]"/>
<suppress checks="[a-zA-Z0-9]*" files="[\\/]src[\\/]test[\\/]resources[\\/]"/>
<suppress checks="[a-zA-Z0-9]*" files="[\\/]build[\\/]generated-sources[\\/]"/>
<suppress checks="[a-zA-Z0-9]*" files="[\\/]src[\\/]main[\\/]resources[\\/]"/>
</suppressions>

View File

@ -25,8 +25,10 @@
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="fileExtensions" value="java, xml, properties"/>
<property name="severity" value="warning"/>
<property name="severity" value="error"/>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
@ -48,7 +50,7 @@
<property name="allowNonPrintableEscapes" value="true"/>
</module>
<module name="LineLength">
<property name="max" value="100"/>
<property name="max" value="120"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>
<module name="AvoidStarImport"/>
@ -61,7 +63,7 @@
</module>
<module name="NeedBraces"/>
<module name="LeftCurly">
<property name="maxLineLength" value="100"/>
<property name="maxLineLength" value="120"/>
</module>
<module name="RightCurly"/>
<module name="RightCurly">
@ -86,9 +88,6 @@
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<module name="EmptyLineSeparator">
<property name="allowNoEmptyLineBetweenFields" value="true"/>
</module>
<module name="SeparatorWrap">
<property name="tokens" value="DOT"/>
<property name="option" value="nl"/>
@ -97,42 +96,19 @@
<property name="tokens" value="COMMA"/>
<property name="option" value="EOL"/>
</module>
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern"
value="Package name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="TypeName">
<message key="name.invalidPattern"
value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="tokens" value="VARIABLE_DEF"/>
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<property name="allowOneCharVarInForLoop" value="true"/>
<message key="name.invalidPattern"
value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
<!-- Checks for Naming Conventions. -->
<!-- See http://checkstyle.sf.net/config_naming.html -->
<module name="ConstantName"/>
<module name="LocalFinalVariableName"/>
<module name="LocalVariableName"/>
<module name="MemberName"/>
<module name="MethodName"/>
<module name="PackageName"/>
<module name="ParameterName"/>
<module name="StaticVariableName"/>
<module name="TypeName"/>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.followed"
@ -157,14 +133,6 @@
<property name="allowedAbbreviationLength" value="1"/>
</module>
<module name="OverloadMethodsDeclarationOrder"/>
<module name="VariableDeclarationUsageDistance"/>
<module name="CustomImportOrder">
<property name="thirdPartyPackageRegExp" value=".*"/>
<property name="specialImportsRegExp" value="com.google"/>
<property name="sortImportsInGroupAlphabetically" value="true"/>
<property name="customImportOrderRules"
value="STATIC###SPECIAL_IMPORTS###THIRD_PARTY_PACKAGE###STANDARD_JAVA_PACKAGE"/>
</module>
<module name="MethodParamPad"/>
<module name="OperatorWrap">
<property name="option" value="NL"/>
@ -180,11 +148,6 @@
</module>
<module name="NonEmptyAtclauseDescription"/>
<module name="JavadocTagContinuationIndentation"/>
<module name="SummaryJavadocCheck">
<property name="forbiddenSummaryFragments"
value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
</module>
<module name="JavadocParagraph"/>
<module name="AtclauseOrder">
<property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
<property name="target" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
@ -195,7 +158,7 @@
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="minLineCount" value="2"/>
<property name="allowedAnnotations" value="Override, Test"/>
<property name="allowedAnnotations" value="Override, Test, Before, After, Parameters, Given, When, BeforeClass, AfterClass, Parameterized"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
</module>
<module name="MethodName">
@ -205,4 +168,5 @@
</module>
<module name="SingleLineJavadoc"/>
</module>
</module>

View File

@ -7,6 +7,7 @@ categories: Behavioral
tags:
- Java
- Gang Of Four
- Difficulty-Intermediate
---
**Also known as:** Action, Transaction

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
<version>1.9.0</version>
</parent>
<artifactId>command</artifactId>
<dependencies>

View File

@ -30,6 +30,9 @@ public abstract class Target {
@Override
public abstract String toString();
/**
* Print status
*/
public void printStatus() {
System.out.println(String.format("%s, [size=%s] [visibility=%s]", this, getSize(),
getVisibility()));

View File

@ -15,12 +15,18 @@ public class Wizard {
public Wizard() {}
/**
* Cast spell
*/
public void castSpell(Command command, Target target) {
System.out.println(this + " casts " + command + " at " + target);
command.execute(target);
undoStack.offerLast(command);
}
/**
* Undo last spell
*/
public void undoLastSpell() {
if (!undoStack.isEmpty()) {
Command previousSpell = undoStack.pollLast();
@ -30,6 +36,9 @@ public class Wizard {
}
}
/**
* Redo last spell
*/
public void redoLastSpell() {
if (!redoStack.isEmpty()) {
Command previousSpell = redoStack.pollLast();

View File

@ -7,6 +7,7 @@ categories: Structural
tags:
- Java
- Gang Of Four
- Difficulty-Intermediate
---
**Intent:** Compose objects into tree structures to represent part-whole

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
<version>1.9.0</version>
</parent>
<artifactId>composite</artifactId>
<dependencies>

View File

@ -24,6 +24,9 @@ public abstract class LetterComposite {
protected abstract void printThisAfter();
/**
* Print
*/
public void print() {
printThisBefore();
for (LetterComposite letter : children) {

View File

@ -9,6 +9,9 @@ import java.util.List;
*/
public class Sentence extends LetterComposite {
/**
* Constructor
*/
public Sentence(List<Word> words) {
for (Word w : words) {
this.add(w);

View File

@ -9,6 +9,9 @@ import java.util.List;
*/
public class Word extends LetterComposite {
/**
* Constructor
*/
public Word(List<Letter> letters) {
for (Letter l : letters) {
this.add(l);

View File

@ -2,8 +2,6 @@ package com.iluwatar.composite;
import org.junit.Test;
import com.iluwatar.composite.App;
/**
*
* Application test

View File

@ -0,0 +1,90 @@
package com.iluwatar.composite;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Date: 12/11/15 - 8:12 PM
*
* @author Jeroen Meulemeester
*/
public class MessengerTest {
/**
* The buffer used to capture every write to {@link System#out}
*/
private ByteArrayOutputStream stdOutBuffer = new ByteArrayOutputStream();
/**
* Keep the original std-out so it can be restored after the test
*/
private final PrintStream realStdOut = System.out;
/**
* Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test
*/
@Before
public void setUp() {
this.stdOutBuffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(stdOutBuffer));
}
/**
* Removed the mocked std-out {@link PrintStream} again from the {@link System} class
*/
@After
public void tearDown() {
System.setOut(realStdOut);
}
/**
* Test the message from the orcs
*/
@Test
public void testMessageFromOrcs() {
final Messenger messenger = new Messenger();
testMessage(
messenger.messageFromOrcs(),
"Where there is a whip there is a way."
);
}
/**
* Test the message from the elves
*/
@Test
public void testMessageFromElves() {
final Messenger messenger = new Messenger();
testMessage(
messenger.messageFromElves(),
"Much wind pours from your mouth."
);
}
/**
* Test if the given composed message matches the expected message
*
* @param composedMessage The composed message, received from the messenger
* @param message The expected message
*/
private void testMessage(final LetterComposite composedMessage, final String message) {
// Test is the composed message has the correct number of words
final String[] words = message.split(" ");
assertNotNull(composedMessage);
assertEquals(words.length, composedMessage.count());
// Print the message to the mocked stdOut ...
composedMessage.print();
// ... and verify if the message matches with the expected one
assertEquals(message, new String(this.stdOutBuffer.toByteArray()).trim());
}
}

View File

@ -3,7 +3,7 @@ layout: pattern
title: Data Access Object
folder: dao
permalink: /patterns/dao/
categories: Architectural
categories: Persistence Tier
tags:
- Java
- Difficulty-Beginner

View File

@ -6,7 +6,7 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
<version>1.9.0</version>
</parent>
<artifactId>dao</artifactId>

View File

@ -21,7 +21,7 @@ import org.apache.log4j.Logger;
*/
public class App {
private static Logger LOGGER = Logger.getLogger(App.class);
private static Logger log = Logger.getLogger(App.class);
/**
* Program entry point.
@ -30,17 +30,17 @@ public class App {
*/
public static void main(final String[] args) {
final CustomerDaoImpl customerDao = new CustomerDaoImpl(generateSampleCustomers());
LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
LOGGER.info("customerDao.getCusterById(2): " + customerDao.getCustomerById(2));
log.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
log.info("customerDao.getCusterById(2): " + customerDao.getCustomerById(2));
final Customer customer = new Customer(4, "Dan", "Danson");
customerDao.addCustomer(customer);
LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
log.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
customer.setFirstName("Daniel");
customer.setLastName("Danielson");
customerDao.updateCustomer(customer);
LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
log.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
customerDao.deleteCustomer(customer);
LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
log.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
}
/**

View File

@ -11,6 +11,9 @@ public class Customer {
private String firstName;
private String lastName;
/**
* Constructor
*/
public Customer(final int id, final String firstName, final String lastName) {
this.id = id;
this.firstName = firstName;
@ -52,10 +55,11 @@ public class Customer {
boolean isEqual = false;
if (this == o) {
isEqual = true;
} else if (o != null && (getClass() == o.getClass())) {
} else if (o != null && getClass() == o.getClass()) {
final Customer customer = (Customer) o;
if (getId() == customer.getId())
if (getId() == customer.getId()) {
isEqual = true;
}
}
return isEqual;
}

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
xmlns:log4j='http://jakarta.apache.org/log4j/'>
xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
</layout>
</appender>
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="console" />
</root>
<root>
<level value="INFO" />
<appender-ref ref="console" />
</root>
</log4j:configuration>

View File

@ -7,6 +7,7 @@ categories: Structural
tags:
- Java
- Gang Of Four
- Difficulty-Beginner
---
**Also known as:** Wrapper

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
<version>1.9.0</version>
</parent>
<artifactId>decorator</artifactId>
<dependencies>
@ -14,5 +14,10 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -2,8 +2,6 @@ package com.iluwatar.decorator;
import org.junit.Test;
import com.iluwatar.decorator.App;
/**
*
* Application test

View File

@ -0,0 +1,36 @@
package com.iluwatar.decorator;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import static org.mockito.internal.verification.VerificationModeFactory.times;
/**
* Date: 12/7/15 - 7:47 PM
*
* @author Jeroen Meulemeester
*/
public class SmartTrollTest {
@Test
public void testSmartTroll() throws Exception {
// Create a normal troll first, but make sure we can spy on it later on.
final Hostile simpleTroll = spy(new Troll());
// Now we want to decorate the troll to make it smarter ...
final Hostile smartTroll = new SmartTroll(simpleTroll);
assertEquals(30, smartTroll.getAttackPower());
verify(simpleTroll, times(1)).getAttackPower();
// Check if the smart troll actions are delegated to the decorated troll
smartTroll.attack();
verify(simpleTroll, times(1)).attack();
smartTroll.fleeBattle();
verify(simpleTroll, times(1)).fleeBattle();
verifyNoMoreInteractions(simpleTroll);
}
}

View File

@ -0,0 +1,62 @@
package com.iluwatar.decorator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static org.mockito.internal.verification.VerificationModeFactory.times;
/**
* Date: 12/7/15 - 7:26 PM
*
* @author Jeroen Meulemeester
*/
public class TrollTest {
/**
* The mocked standard out stream, required since the actions don't have any influence on other
* objects, except for writing to the std-out using {@link System#out}
*/
private final PrintStream stdOutMock = mock(PrintStream.class);
/**
* Keep the original std-out so it can be restored after the test
*/
private final PrintStream stdOutOrig = System.out;
/**
* Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test
*/
@Before
public void setUp() {
System.setOut(this.stdOutMock);
}
/**
* Removed the mocked std-out {@link PrintStream} again from the {@link System} class
*/
@After
public void tearDown() {
System.setOut(this.stdOutOrig);
}
@Test
public void testTrollActions() throws Exception {
final Troll troll = new Troll();
assertEquals(10, troll.getAttackPower());
troll.attack();
verify(this.stdOutMock, times(1)).println(eq("The troll swings at you with a club!"));
troll.fleeBattle();
verify(this.stdOutMock, times(1)).println(eq("The troll shrieks in horror and runs away!"));
verifyNoMoreInteractions(this.stdOutMock);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@ -0,0 +1,83 @@
<?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">
<class id="1" language="java" name="com.iluwatar.delegation.simple.printers.HpPrinter" project="delegation"
file="/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="764" y="272"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="2" language="java" name="com.iluwatar.delegation.simple.printers.EpsonPrinter" project="delegation"
file="/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="511" y="270"/>
<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.delegation.simple.printers.CanonPrinter" project="delegation"
file="/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="252" y="275"/>
<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="4" language="java" name="com.iluwatar.delegation.simple.Printer" project="delegation"
file="/delegation/src/main/java/com/iluwatar/delegation/simple/Printer.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="524" y="89"/>
<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.delegation.simple.PrinterController" project="delegation"
file="/delegation/src/main/java/com/iluwatar/delegation/simple/PrinterController.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="112" y="90"/>
<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="6">
<end type="SOURCE" refId="2"/>
<end type="TARGET" refId="4"/>
</realization>
<association id="7">
<end type="SOURCE" refId="5" navigable="false">
<attribute id="8" name="printer"/>
<multiplicity id="9" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="4" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<realization id="10">
<end type="SOURCE" refId="5"/>
<end type="TARGET" refId="4"/>
</realization>
<realization id="11">
<end type="SOURCE" refId="3"/>
<end type="TARGET" refId="4"/>
</realization>
<realization id="12">
<end type="SOURCE" refId="1"/>
<end type="TARGET" refId="4"/>
</realization>
<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>

27
delegation/index.md Normal file
View File

@ -0,0 +1,27 @@
---
layout: pattern
title: Delegation
folder: delegation
permalink: /patterns/delegation/
categories: Behavioral
tags:
- Java
- Difficulty-Beginner
---
**Also known as:** Proxy Pattern
**Intent:** It is a technique where an object expresses certain behavior to the outside but in
reality delegates responsibility for implementing that behaviour to an associated object.
![alt text](./etc/delegation.png "Delegate")
**Applicability:** Use the Delegate pattern in order to achieve the following
* Reduce the coupling of methods to their class
* Components that behave identically, but realize that this situation can change in the future.
**Credits**
* [Delegate Pattern: Wikipedia ](https://en.wikipedia.org/wiki/Delegation_pattern)
* [Proxy Pattern: Wikipedia ](https://en.wikipedia.org/wiki/Proxy_pattern)

27
delegation/pom.xml Normal file
View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.9.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>delegation</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.stefanbirkner</groupId>
<artifactId>system-rules</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,38 @@
package com.iluwatar.delegation.simple;
import com.iluwatar.delegation.simple.printers.CanonPrinter;
import com.iluwatar.delegation.simple.printers.EpsonPrinter;
import com.iluwatar.delegation.simple.printers.HpPrinter;
/**
* The delegate pattern provides a mechanism to abstract away the implementation and control of the desired action.
* The class being called in this case {@link PrinterController} is not responsible for the actual desired action,
* but is actually delegated to a helper class either {@link CanonPrinter}, {@link EpsonPrinter} or {@link HpPrinter}.
* The consumer does not have or require knowledge of the actual class carrying out the action, only the
* container on which they are calling.
*
* In this example the delegates are {@link EpsonPrinter}, {@link HpPrinter} and {@link CanonPrinter} they all implement
* {@link Printer}. The {@link PrinterController} class also implements {@link Printer}. However neither provide the
* functionality of {@link Printer} by printing to the screen, they actually call upon the instance of {@link Printer}
* that they were instantiated with. Therefore delegating the behaviour to another class.
*/
public class App {
public static final String MESSAGE_TO_PRINT = "hello world";
/**
* Program entry point
*
* @param args command line args
*/
public static void main(String[] args) {
PrinterController hpPrinterController = new PrinterController(new HpPrinter());
PrinterController canonPrinterController = new PrinterController(new CanonPrinter());
PrinterController epsonPrinterController = new PrinterController(new EpsonPrinter());
hpPrinterController.print(MESSAGE_TO_PRINT);
canonPrinterController.print(MESSAGE_TO_PRINT);
epsonPrinterController.print(MESSAGE_TO_PRINT);
}
}

View File

@ -0,0 +1,23 @@
package com.iluwatar.delegation.simple;
import com.iluwatar.delegation.simple.printers.CanonPrinter;
import com.iluwatar.delegation.simple.printers.EpsonPrinter;
import com.iluwatar.delegation.simple.printers.HpPrinter;
/**
* Interface that both the Controller and the Delegate will implement.
*
* @see CanonPrinter
* @see EpsonPrinter
* @see HpPrinter
*/
public interface Printer {
/**
* Method that takes a String to print to the screen. This will be implemented on both the
* controller and the delegate allowing the controller to call the same method on the delegate class.
*
* @param message to be printed to the screen
*/
void print(final String message);
}

View File

@ -0,0 +1,23 @@
package com.iluwatar.delegation.simple;
public class PrinterController implements Printer {
private final Printer printer;
public PrinterController(Printer printer) {
this.printer = printer;
}
/**
* This method is implemented from {@link Printer} however instead on providing an
* implementation, it instead calls upon the class passed through the constructor. This is the delegate,
* hence the pattern. Therefore meaning that the caller does not care of the implementing class only the owning
* controller.
*
* @param message to be printed to the screen
*/
@Override
public void print(String message) {
printer.print(message);
}
}

View File

@ -0,0 +1,21 @@
package com.iluwatar.delegation.simple.printers;
import com.iluwatar.delegation.simple.Printer;
/**
* Specialised Implementation of {@link Printer} for a Canon Printer, in
* this case the message to be printed is appended to "Canon Printer : "
*
* @see Printer
*/
public class CanonPrinter implements Printer {
/**
* {@inheritDoc}
*/
@Override
public void print(String message) {
System.out.print("Canon Printer : " + message);
}
}

View File

@ -0,0 +1,21 @@
package com.iluwatar.delegation.simple.printers;
import com.iluwatar.delegation.simple.Printer;
/**
* Specialised Implementation of {@link Printer} for a Epson Printer, in
* this case the message to be printed is appended to "Epson Printer : "
*
* @see Printer
*/
public class EpsonPrinter implements Printer {
/**
* {@inheritDoc}
*/
@Override
public void print(String message) {
System.out.print("Epson Printer : " + message);
}
}

View File

@ -0,0 +1,21 @@
package com.iluwatar.delegation.simple.printers;
import com.iluwatar.delegation.simple.Printer;
/**
* Specialised Implementation of {@link Printer} for a HP Printer, in
* this case the message to be printed is appended to "HP Printer : "
*
* @see Printer
*/
public class HpPrinter implements Printer {
/**
* {@inheritDoc}
*/
@Override
public void print(String message) {
System.out.print("HP Printer : " + message);
}
}

View File

@ -0,0 +1,13 @@
package com.iluwatar.delegation.simple;
import org.junit.Test;
public class AppTest {
@Test
public void test() {
String[] args = {};
App.main(args);
}
}

View File

@ -0,0 +1,43 @@
package com.iluwatar.delegation.simple;
import com.iluwatar.delegation.simple.printers.CanonPrinter;
import com.iluwatar.delegation.simple.printers.EpsonPrinter;
import com.iluwatar.delegation.simple.printers.HpPrinter;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.SystemOutRule;
import static org.junit.Assert.assertEquals;
public class DelegateTest {
private static final String MESSAGE = "Test Message Printed";
@Rule
public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
@Test
public void testCanonPrinter() throws Exception {
PrinterController printerController = new PrinterController(new CanonPrinter());
printerController.print(MESSAGE);
assertEquals("Canon Printer : Test Message Printed", systemOutRule.getLog());
}
@Test
public void testHpPrinter() throws Exception {
PrinterController printerController = new PrinterController(new HpPrinter());
printerController.print(MESSAGE);
assertEquals("HP Printer : Test Message Printed", systemOutRule.getLog());
}
@Test
public void testEpsonPrinter() throws Exception {
PrinterController printerController = new PrinterController(new EpsonPrinter());
printerController.print(MESSAGE);
assertEquals("Epson Printer : Test Message Printed", systemOutRule.getLog());
}
}

View File

@ -4,7 +4,9 @@ title: Dependency Injection
folder: dependency-injection
permalink: /patterns/dependency-injection/
categories: Behavioral
tags: Java
tags:
- Java
- Difficulty-Beginner
---
**Intent:** Dependency Injection is a software design pattern in which one or

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