Compare commits
168 Commits
Author | SHA1 | Date | |
---|---|---|---|
e4458c1b17 | |||
30e09a8dd9 | |||
f987c7253b | |||
ad714294dd | |||
623c2081cd | |||
542a832a66 | |||
444eb07e26 | |||
fd8c05846f | |||
47709e24b9 | |||
09d3a82884 | |||
997bfba3b2 | |||
6326c1742d | |||
2e2707862a | |||
1d9aff4071 | |||
5611f26c77 | |||
d0cdf84936 | |||
a375b2d28b | |||
fcfdbe71f5 | |||
52c483f1d0 | |||
c72faeb67e | |||
299d612b9b | |||
9d4c3154b1 | |||
a3b1265921 | |||
dca68511e8 | |||
42a1dc69ca | |||
47e1cd710c | |||
b3d1c2b2ed | |||
3e20a2afa8 | |||
4c938ab8a5 | |||
8f6f171a3f | |||
b4dcec45ef | |||
dec5ff22fc | |||
7b323e9cb4 | |||
a0af0a1a76 | |||
7c6e1fc3d8 | |||
45cecf68c4 | |||
d7580f5530 | |||
58b8a06561 | |||
befe509582 | |||
17b889c31d | |||
52192de909 | |||
8b020837ea | |||
b369812511 | |||
52d6e20ad9 | |||
749880e3b9 | |||
41593774c6 | |||
0bc722f797 | |||
fcadb223ce | |||
c842f88eb7 | |||
6d516d5124 | |||
9544dd321a | |||
d623e9c8fd | |||
e27de33f75 | |||
7ac7e3b097 | |||
fefb51c46e | |||
58547fae8f | |||
30676f8d4f | |||
483db04cef | |||
fac10dc454 | |||
982f9f5e31 | |||
74d1823078 | |||
f59f18091e | |||
5f033be54f | |||
df911baf36 | |||
32e7181478 | |||
c8a750df49 | |||
191078735f | |||
fa6a6006c3 | |||
a49dbefb56 | |||
fb0617e9c5 | |||
84fd2348ea | |||
f0ff8ad4b3 | |||
c3184255bf | |||
bdacfe30c1 | |||
30363cbb7f | |||
3d8c64d76d | |||
78fcd63271 | |||
30bc25b5bf | |||
6b1356a160 | |||
cec9a99410 | |||
9fbb085985 | |||
6e496e7c86 | |||
e3e0e32e92 | |||
531158c836 | |||
6fe01e73b2 | |||
69c9374669 | |||
a57a71b09c | |||
719f80a0d6 | |||
2c82bd9450 | |||
5948a82cf2 | |||
a0151826ad | |||
33fe90d177 | |||
25cacdbbc9 | |||
323e4c8751 | |||
de78490d29 | |||
9059d2b96c | |||
dbca06a9e7 | |||
ca14e8ddad | |||
3dc370e2d1 | |||
4181514c65 | |||
df69a8f986 | |||
885d5bb7dd | |||
1b74e0ff67 | |||
94f80d1868 | |||
c837ffe234 | |||
2edc1898b1 | |||
29fc56002a | |||
0643289c74 | |||
2c0a5e8703 | |||
a3372febd0 | |||
7df65adbfc | |||
d7dd8d42af | |||
4e7a8fdaca | |||
6e59d9554f | |||
e85308fbc4 | |||
10a94cc91c | |||
e2d8079b36 | |||
8367c83aca | |||
875e5b872c | |||
1fa617d08d | |||
6c1f025d0f | |||
601964a2d1 | |||
1884df525b | |||
507b89d5e4 | |||
02d6754804 | |||
e709a196bd | |||
f018d13c39 | |||
33b41f872e | |||
119d264779 | |||
9a85dfe9df | |||
5bec63659f | |||
9d4fff6029 | |||
092d48d150 | |||
6b99f2669e | |||
ced317bc9d | |||
e5614e5a20 | |||
012b638023 | |||
b577890db4 | |||
8ba0192864 | |||
899b9617c9 | |||
d0fca6d318 | |||
7885380633 | |||
230c02fb24 | |||
b97e9207a7 | |||
8519e13de6 | |||
ba3f583467 | |||
142274f3f7 | |||
5b06c52fff | |||
033f8e740d | |||
34528173b7 | |||
fdbfa9e8ee | |||
bf65168776 | |||
043a610754 | |||
27199325ec | |||
960b568fbb | |||
c02e65fa3a | |||
fe63c9cec4 | |||
7e4f04602e | |||
306b1f3d31 | |||
449340bd2b | |||
3af06a3a3a | |||
e7b6542134 | |||
16a8c85af6 | |||
95c16200e7 | |||
c0c21ebd91 | |||
25c1f87d46 | |||
c6ca80b25f | |||
ac5c1967df |
13
CODE_COVERAGE.md
Normal file
13
CODE_COVERAGE.md
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
# Code Coverage Report generation
|
||||||
|
|
||||||
|
To generate the code coverage report, execute the following command:
|
||||||
|
> mvn clean verify
|
||||||
|
|
||||||
|
This will generate code coverage report in each of the modules. In order to view the same, open the following file in your browser.
|
||||||
|
> target/site/jacoco/index.html
|
||||||
|
|
||||||
|
Please note that the above folder is created under each of the modules. For example:
|
||||||
|
* adapter/target/site/jacoco/index.html
|
||||||
|
* busniess-delegate/target/site/jacoco/index.html
|
||||||
|
|
||||||
|
|
4
CONTRIBUTING.MD
Normal file
4
CONTRIBUTING.MD
Normal 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.
|
@ -2,11 +2,10 @@
|
|||||||
that smart and dearly wants an empty line before a heading to be able to
|
that smart and dearly wants an empty line before a heading to be able to
|
||||||
display it as such, e.g. website) -->
|
display it as such, e.g. website) -->
|
||||||
|
|
||||||
# Design pattern samples in Java
|
# Design patterns implemented in Java
|
||||||
|
|
||||||
[](https://travis-ci.org/iluwatar/java-design-patterns)
|
[](https://travis-ci.org/iluwatar/java-design-patterns)
|
||||||
[](https://coveralls.io/r/iluwatar/java-design-patterns?branch=master)
|
[](https://coveralls.io/r/iluwatar/java-design-patterns?branch=master)
|
||||||
[](https://scan.coverity.com/projects/5634)
|
|
||||||
[](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
[](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
|
|
||||||
# Introduction
|
# Introduction
|
||||||
@ -40,7 +39,7 @@ patterns by any of the following approaches
|
|||||||
|
|
||||||
# How to contribute
|
# 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
|
# Credits
|
||||||
|
|
||||||
|
@ -7,8 +7,11 @@ categories: Creational
|
|||||||
tags:
|
tags:
|
||||||
- Java
|
- Java
|
||||||
- Gang Of Four
|
- Gang Of Four
|
||||||
|
- Difficulty-Intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
|
**Also known as:** Kit
|
||||||
|
|
||||||
**Intent:** Provide an interface for creating families of related or dependent
|
**Intent:** Provide an interface for creating families of related or dependent
|
||||||
objects without specifying their concrete classes.
|
objects without specifying their concrete classes.
|
||||||
|
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.iluwatar</groupId>
|
<groupId>com.iluwatar</groupId>
|
||||||
<artifactId>java-design-patterns</artifactId>
|
<artifactId>java-design-patterns</artifactId>
|
||||||
<version>1.7.0</version>
|
<version>1.9.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>abstract-factory</artifactId>
|
<artifactId>abstract-factory</artifactId>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -1,82 +1,105 @@
|
|||||||
package com.iluwatar.abstractfactory;
|
package com.iluwatar.abstractfactory;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* The Abstract Factory pattern provides a way to encapsulate a group of individual
|
* The Abstract Factory pattern provides a way to encapsulate a group of individual factories that have a common theme
|
||||||
* factories that have a common theme without specifying their concrete classes. In
|
* without specifying their concrete classes. In normal usage, the client software creates a concrete implementation of
|
||||||
* normal usage, the client software creates a concrete implementation of the abstract
|
* the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part
|
||||||
* factory and then uses the generic interface of the factory to create the concrete
|
* of the theme. The client does not know (or care) which concrete objects it gets from each of these internal
|
||||||
* objects that are part of the theme. The client does not know (or care) which
|
* factories, since it uses only the generic interfaces of their products. This pattern separates the details of
|
||||||
* concrete objects it gets from each of these internal factories, since it uses only
|
* implementation of a set of objects from their general usage and relies on object composition, as object creation is
|
||||||
* the generic interfaces of their products. This pattern separates the details of
|
* implemented in methods exposed in the factory interface.
|
||||||
* 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>
|
* <p>
|
||||||
* The essence of the Abstract Factory pattern is a factory interface
|
* The essence of the Abstract Factory pattern is a factory interface ({@link KingdomFactory}) and its implementations (
|
||||||
* ({@link KingdomFactory}) and its implementations ({@link ElfKingdomFactory},
|
* {@link ElfKingdomFactory}, {@link OrcKingdomFactory}). The example uses both concrete implementations to create a
|
||||||
* {@link OrcKingdomFactory}). The example uses both concrete implementations to
|
* king, a castle and an army.
|
||||||
* create a king, a castle and an army.
|
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class App {
|
public class App {
|
||||||
|
|
||||||
private King king;
|
private King king;
|
||||||
private Castle castle;
|
private Castle castle;
|
||||||
private Army army;
|
private Army army;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates kingdom
|
||||||
|
*/
|
||||||
|
public void createKingdom(final KingdomFactory factory) {
|
||||||
|
setKing(factory.createKing());
|
||||||
|
setCastle(factory.createCastle());
|
||||||
|
setArmy(factory.createArmy());
|
||||||
|
}
|
||||||
|
|
||||||
|
ElfKingdomFactory getElfKingdomFactory() {
|
||||||
|
return new ElfKingdomFactory();
|
||||||
|
}
|
||||||
|
|
||||||
|
OrcKingdomFactory getOrcKingdomFactory() {
|
||||||
|
return new OrcKingdomFactory();
|
||||||
|
}
|
||||||
|
|
||||||
|
King getKing(final KingdomFactory factory) {
|
||||||
|
return factory.createKing();
|
||||||
|
}
|
||||||
|
|
||||||
|
public King getKing() {
|
||||||
|
return king;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setKing(final King king) {
|
||||||
|
this.king = king;
|
||||||
|
}
|
||||||
|
|
||||||
|
Castle getCastle(final KingdomFactory factory) {
|
||||||
|
return factory.createCastle();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Castle getCastle() {
|
||||||
|
return castle;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setCastle(final Castle castle) {
|
||||||
|
this.castle = castle;
|
||||||
|
}
|
||||||
|
|
||||||
|
Army getArmy(final KingdomFactory factory) {
|
||||||
|
return factory.createArmy();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Army getArmy() {
|
||||||
|
return army;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setArmy(final Army army) {
|
||||||
|
this.army = army;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Program entry point
|
||||||
|
*
|
||||||
|
* @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());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates kingdom
|
|
||||||
* @param factory
|
|
||||||
*/
|
|
||||||
public void createKingdom(final KingdomFactory factory) {
|
|
||||||
setKing(factory.createKing());
|
|
||||||
setCastle(factory.createCastle());
|
|
||||||
setArmy(factory.createArmy());
|
|
||||||
}
|
|
||||||
|
|
||||||
ElfKingdomFactory getElfKingdomFactory() {
|
|
||||||
return new ElfKingdomFactory();
|
|
||||||
}
|
|
||||||
|
|
||||||
OrcKingdomFactory getOrcKingdomFactory() {
|
|
||||||
return new OrcKingdomFactory();
|
|
||||||
}
|
|
||||||
|
|
||||||
King getKing(final KingdomFactory factory) {
|
|
||||||
return factory.createKing();
|
|
||||||
}
|
|
||||||
|
|
||||||
Castle getCastle(final KingdomFactory factory) {
|
|
||||||
return factory.createCastle();
|
|
||||||
}
|
|
||||||
|
|
||||||
Army getArmy(final KingdomFactory factory) {
|
|
||||||
return factory.createArmy();
|
|
||||||
}
|
|
||||||
|
|
||||||
public King getKing() {
|
|
||||||
return king;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void setKing(final King king) {
|
|
||||||
this.king = king;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Castle getCastle() {
|
|
||||||
return castle;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void setCastle(final Castle castle) {
|
|
||||||
this.castle = castle;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Army getArmy() {
|
|
||||||
return army;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void setArmy(final Army army) {
|
|
||||||
this.army = army;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -7,5 +7,5 @@ package com.iluwatar.abstractfactory;
|
|||||||
*/
|
*/
|
||||||
public interface Army {
|
public interface Army {
|
||||||
|
|
||||||
String getDescription();
|
String getDescription();
|
||||||
}
|
}
|
||||||
|
@ -7,5 +7,5 @@ package com.iluwatar.abstractfactory;
|
|||||||
*/
|
*/
|
||||||
public interface Castle {
|
public interface Castle {
|
||||||
|
|
||||||
String getDescription();
|
String getDescription();
|
||||||
}
|
}
|
||||||
|
@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory;
|
|||||||
*/
|
*/
|
||||||
public class ElfArmy implements Army {
|
public class ElfArmy implements Army {
|
||||||
|
|
||||||
static final String DESCRIPTION = "This is the Elven Army!";
|
static final String DESCRIPTION = "This is the Elven Army!";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription() {
|
||||||
return DESCRIPTION;
|
return DESCRIPTION;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory;
|
|||||||
*/
|
*/
|
||||||
public class ElfCastle implements Castle {
|
public class ElfCastle implements Castle {
|
||||||
|
|
||||||
static final String DESCRIPTION = "This is the Elven castle!";
|
static final String DESCRIPTION = "This is the Elven castle!";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription() {
|
||||||
return DESCRIPTION;
|
return DESCRIPTION;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory;
|
|||||||
*/
|
*/
|
||||||
public class ElfKing implements King {
|
public class ElfKing implements King {
|
||||||
|
|
||||||
static final String DESCRIPTION = "This is the Elven king!";
|
static final String DESCRIPTION = "This is the Elven king!";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription() {
|
||||||
return DESCRIPTION;
|
return DESCRIPTION;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,16 +7,16 @@ package com.iluwatar.abstractfactory;
|
|||||||
*/
|
*/
|
||||||
public class ElfKingdomFactory implements KingdomFactory {
|
public class ElfKingdomFactory implements KingdomFactory {
|
||||||
|
|
||||||
public Castle createCastle() {
|
public Castle createCastle() {
|
||||||
return new ElfCastle();
|
return new ElfCastle();
|
||||||
}
|
}
|
||||||
|
|
||||||
public King createKing() {
|
public King createKing() {
|
||||||
return new ElfKing();
|
return new ElfKing();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Army createArmy() {
|
public Army createArmy() {
|
||||||
return new ElfArmy();
|
return new ElfArmy();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -7,5 +7,5 @@ package com.iluwatar.abstractfactory;
|
|||||||
*/
|
*/
|
||||||
public interface King {
|
public interface King {
|
||||||
|
|
||||||
String getDescription();
|
String getDescription();
|
||||||
}
|
}
|
||||||
|
@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory;
|
|||||||
*/
|
*/
|
||||||
public interface KingdomFactory {
|
public interface KingdomFactory {
|
||||||
|
|
||||||
Castle createCastle();
|
Castle createCastle();
|
||||||
|
|
||||||
King createKing();
|
King createKing();
|
||||||
|
|
||||||
Army createArmy();
|
Army createArmy();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory;
|
|||||||
*/
|
*/
|
||||||
public class OrcArmy implements Army {
|
public class OrcArmy implements Army {
|
||||||
|
|
||||||
static final String DESCRIPTION = "This is the Orc Army!";
|
static final String DESCRIPTION = "This is the Orc Army!";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription() {
|
||||||
return DESCRIPTION;
|
return DESCRIPTION;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory;
|
|||||||
*/
|
*/
|
||||||
public class OrcCastle implements Castle {
|
public class OrcCastle implements Castle {
|
||||||
|
|
||||||
static final String DESCRIPTION = "This is the Orc castle!";
|
static final String DESCRIPTION = "This is the Orc castle!";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription() {
|
||||||
return DESCRIPTION;
|
return DESCRIPTION;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory;
|
|||||||
*/
|
*/
|
||||||
public class OrcKing implements King {
|
public class OrcKing implements King {
|
||||||
|
|
||||||
static final String DESCRIPTION = "This is the Orc king!";
|
static final String DESCRIPTION = "This is the Orc king!";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getDescription() {
|
public String getDescription() {
|
||||||
return DESCRIPTION;
|
return DESCRIPTION;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,16 +7,15 @@ package com.iluwatar.abstractfactory;
|
|||||||
*/
|
*/
|
||||||
public class OrcKingdomFactory implements KingdomFactory {
|
public class OrcKingdomFactory implements KingdomFactory {
|
||||||
|
|
||||||
public Castle createCastle() {
|
public Castle createCastle() {
|
||||||
return new OrcCastle();
|
return new OrcCastle();
|
||||||
}
|
}
|
||||||
|
|
||||||
public King createKing() {
|
public King createKing() {
|
||||||
return new OrcKing();
|
return new OrcKing();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Army createArmy() {
|
|
||||||
return new OrcArmy();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
public Army createArmy() {
|
||||||
|
return new OrcArmy();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
package com.iluwatar.abstractfactory;
|
package com.iluwatar.abstractfactory;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
@ -7,71 +8,71 @@ import org.junit.Test;
|
|||||||
|
|
||||||
public class AppTest {
|
public class AppTest {
|
||||||
|
|
||||||
private App app = new App();
|
private App app = new App();
|
||||||
private KingdomFactory elfFactory;
|
private KingdomFactory elfFactory;
|
||||||
private KingdomFactory orcFactory;
|
private KingdomFactory orcFactory;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() {
|
public void setUp() {
|
||||||
elfFactory = app.getElfKingdomFactory();
|
elfFactory = app.getElfKingdomFactory();
|
||||||
orcFactory = app.getOrcKingdomFactory();
|
orcFactory = app.getOrcKingdomFactory();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void king() {
|
public void king() {
|
||||||
final King elfKing = app.getKing(elfFactory);
|
final King elfKing = app.getKing(elfFactory);
|
||||||
assertTrue(elfKing instanceof ElfKing);
|
assertTrue(elfKing instanceof ElfKing);
|
||||||
assertEquals(ElfKing.DESCRIPTION, elfKing.getDescription());
|
assertEquals(ElfKing.DESCRIPTION, elfKing.getDescription());
|
||||||
final King orcKing = app.getKing(orcFactory);
|
final King orcKing = app.getKing(orcFactory);
|
||||||
assertTrue(orcKing instanceof OrcKing);
|
assertTrue(orcKing instanceof OrcKing);
|
||||||
assertEquals(OrcKing.DESCRIPTION, orcKing.getDescription());
|
assertEquals(OrcKing.DESCRIPTION, orcKing.getDescription());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void castle() {
|
public void castle() {
|
||||||
final Castle elfCastle = app.getCastle(elfFactory);
|
final Castle elfCastle = app.getCastle(elfFactory);
|
||||||
assertTrue(elfCastle instanceof ElfCastle);
|
assertTrue(elfCastle instanceof ElfCastle);
|
||||||
assertEquals(ElfCastle.DESCRIPTION, elfCastle.getDescription());
|
assertEquals(ElfCastle.DESCRIPTION, elfCastle.getDescription());
|
||||||
final Castle orcCastle = app.getCastle(orcFactory);
|
final Castle orcCastle = app.getCastle(orcFactory);
|
||||||
assertTrue(orcCastle instanceof OrcCastle);
|
assertTrue(orcCastle instanceof OrcCastle);
|
||||||
assertEquals(OrcCastle.DESCRIPTION, orcCastle.getDescription());
|
assertEquals(OrcCastle.DESCRIPTION, orcCastle.getDescription());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void army() {
|
public void army() {
|
||||||
final Army elfArmy = app.getArmy(elfFactory);
|
final Army elfArmy = app.getArmy(elfFactory);
|
||||||
assertTrue(elfArmy instanceof ElfArmy);
|
assertTrue(elfArmy instanceof ElfArmy);
|
||||||
assertEquals(ElfArmy.DESCRIPTION, elfArmy.getDescription());
|
assertEquals(ElfArmy.DESCRIPTION, elfArmy.getDescription());
|
||||||
final Army orcArmy = app.getArmy(orcFactory);
|
final Army orcArmy = app.getArmy(orcFactory);
|
||||||
assertTrue(orcArmy instanceof OrcArmy);
|
assertTrue(orcArmy instanceof OrcArmy);
|
||||||
assertEquals(OrcArmy.DESCRIPTION, orcArmy.getDescription());
|
assertEquals(OrcArmy.DESCRIPTION, orcArmy.getDescription());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void createElfKingdom() {
|
public void createElfKingdom() {
|
||||||
app.createKingdom(elfFactory);
|
app.createKingdom(elfFactory);
|
||||||
final King king = app.getKing();
|
final King king = app.getKing();
|
||||||
final Castle castle = app.getCastle();
|
final Castle castle = app.getCastle();
|
||||||
final Army army = app.getArmy();
|
final Army army = app.getArmy();
|
||||||
assertTrue(king instanceof ElfKing);
|
assertTrue(king instanceof ElfKing);
|
||||||
assertEquals(ElfKing.DESCRIPTION, king.getDescription());
|
assertEquals(ElfKing.DESCRIPTION, king.getDescription());
|
||||||
assertTrue(castle instanceof ElfCastle);
|
assertTrue(castle instanceof ElfCastle);
|
||||||
assertEquals(ElfCastle.DESCRIPTION, castle.getDescription());
|
assertEquals(ElfCastle.DESCRIPTION, castle.getDescription());
|
||||||
assertTrue(army instanceof ElfArmy);
|
assertTrue(army instanceof ElfArmy);
|
||||||
assertEquals(ElfArmy.DESCRIPTION, army.getDescription());
|
assertEquals(ElfArmy.DESCRIPTION, army.getDescription());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void createOrcKingdom() {
|
public void createOrcKingdom() {
|
||||||
app.createKingdom(orcFactory);
|
app.createKingdom(orcFactory);
|
||||||
final King king = app.getKing();
|
final King king = app.getKing();
|
||||||
final Castle castle = app.getCastle();
|
final Castle castle = app.getCastle();
|
||||||
final Army army = app.getArmy();
|
final Army army = app.getArmy();
|
||||||
assertTrue(king instanceof OrcKing);
|
assertTrue(king instanceof OrcKing);
|
||||||
assertEquals(OrcKing.DESCRIPTION, king.getDescription());
|
assertEquals(OrcKing.DESCRIPTION, king.getDescription());
|
||||||
assertTrue(castle instanceof OrcCastle);
|
assertTrue(castle instanceof OrcCastle);
|
||||||
assertEquals(OrcCastle.DESCRIPTION, castle.getDescription());
|
assertEquals(OrcCastle.DESCRIPTION, castle.getDescription());
|
||||||
assertTrue(army instanceof OrcArmy);
|
assertTrue(army instanceof OrcArmy);
|
||||||
assertEquals(OrcArmy.DESCRIPTION, army.getDescription());
|
assertEquals(OrcArmy.DESCRIPTION, army.getDescription());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Binary file not shown.
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
@ -1,61 +1,61 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
|
<class-diagram version="1.1.9" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
|
||||||
realizations="true" associations="true" dependencies="false" nesting-relationships="true">
|
associations="true" dependencies="false" nesting-relationships="true" router="FAN">
|
||||||
<class id="1" language="java" name="com.iluwatar.adapter.GnomeEngineeringManager" project="adapter"
|
<class id="1" language="java" name="com.iluwatar.adapter.FishingBoat" project="adapter"
|
||||||
file="/adapter/src/main/java/com/iluwatar/adapter/GnomeEngineeringManager.java" binary="false" corner="BOTTOM_RIGHT">
|
file="/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java" binary="false" corner="BOTTOM_RIGHT">
|
||||||
<position height="106" width="224" x="110" y="210"/>
|
<position height="-1" width="-1" x="656" y="355"/>
|
||||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||||
sort-features="false" accessors="true" visibility="true">
|
sort-features="false" accessors="true" visibility="true">
|
||||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||||
</display>
|
</display>
|
||||||
</class>
|
</class>
|
||||||
<interface id="2" language="java" name="com.iluwatar.adapter.Engineer" project="adapter"
|
<class id="2" language="java" name="com.iluwatar.adapter.Captain" project="adapter"
|
||||||
file="/adapter/src/main/java/com/iluwatar/adapter/Engineer.java" binary="false" corner="BOTTOM_RIGHT">
|
file="/adapter/src/main/java/com/iluwatar/adapter/Captain.java" binary="false" corner="BOTTOM_RIGHT">
|
||||||
<position height="88" width="141" x="110" y="356"/>
|
<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"
|
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||||
sort-features="false" accessors="true" visibility="true">
|
sort-features="false" accessors="true" visibility="true">
|
||||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||||
</display>
|
</display>
|
||||||
</interface>
|
</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">
|
<realization id="5">
|
||||||
<end type="SOURCE" refId="1"/>
|
<end type="SOURCE" refId="2"/>
|
||||||
<end type="TARGET" refId="2"/>
|
<end type="TARGET" refId="4"/>
|
||||||
</realization>
|
</realization>
|
||||||
<realization id="6">
|
<association id="6">
|
||||||
<end type="SOURCE" refId="3"/>
|
<end type="SOURCE" refId="3" navigable="false">
|
||||||
<end type="TARGET" refId="2"/>
|
<attribute id="7" name="boat"/>
|
||||||
</realization>
|
<multiplicity id="8" minimum="0" maximum="1"/>
|
||||||
<association id="7">
|
|
||||||
<end type="SOURCE" refId="1" navigable="false">
|
|
||||||
<attribute id="8" name="engineer"/>
|
|
||||||
<multiplicity id="9" minimum="0" maximum="1"/>
|
|
||||||
</end>
|
</end>
|
||||||
<end type="TARGET" refId="2" navigable="true"/>
|
<end type="TARGET" refId="1" navigable="true"/>
|
||||||
<display labels="true" multiplicity="true"/>
|
<display labels="true" multiplicity="true"/>
|
||||||
</association>
|
</association>
|
||||||
|
<realization id="9">
|
||||||
|
<end type="SOURCE" refId="3"/>
|
||||||
|
<end type="TARGET" refId="4"/>
|
||||||
|
</realization>
|
||||||
<association id="10">
|
<association id="10">
|
||||||
<end type="SOURCE" refId="3" navigable="false">
|
<end type="SOURCE" refId="2" navigable="false">
|
||||||
<attribute id="11" name="glider"/>
|
<attribute id="11" name="battleship"/>
|
||||||
<multiplicity id="12" minimum="0" maximum="1"/>
|
<multiplicity id="12" minimum="0" maximum="1"/>
|
||||||
</end>
|
</end>
|
||||||
<end type="TARGET" refId="4" navigable="true"/>
|
<end type="TARGET" refId="4" navigable="true"/>
|
||||||
|
Binary file not shown.
Before Width: | Height: | Size: 29 KiB |
@ -7,13 +7,16 @@ categories: Structural
|
|||||||
tags:
|
tags:
|
||||||
- Java
|
- Java
|
||||||
- Gang Of Four
|
- Gang Of Four
|
||||||
|
- Difficulty-Beginner
|
||||||
---
|
---
|
||||||
|
|
||||||
|
**Also known as:** Wrapper
|
||||||
|
|
||||||
**Intent:** Convert the interface of a class into another interface the clients
|
**Intent:** Convert the interface of a class into another interface the clients
|
||||||
expect. Adapter lets classes work together that couldn't otherwise because of
|
expect. Adapter lets classes work together that couldn't otherwise because of
|
||||||
incompatible interfaces.
|
incompatible interfaces.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
**Applicability:** Use the Adapter pattern when
|
**Applicability:** Use the Adapter pattern when
|
||||||
|
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.iluwatar</groupId>
|
<groupId>com.iluwatar</groupId>
|
||||||
<artifactId>java-design-patterns</artifactId>
|
<artifactId>java-design-patterns</artifactId>
|
||||||
<version>1.7.0</version>
|
<version>1.9.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>adapter</artifactId>
|
<artifactId>adapter</artifactId>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -14,5 +14,10 @@
|
|||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mockito</groupId>
|
||||||
|
<artifactId>mockito-core</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</project>
|
</project>
|
||||||
|
@ -1,31 +1,38 @@
|
|||||||
package com.iluwatar.adapter;
|
package com.iluwatar.adapter;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* 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.
|
||||||
*
|
*
|
||||||
* 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.
|
|
||||||
* <p>
|
* <p>
|
||||||
* There are two variations of the Adapter pattern: The class adapter implements
|
* There are two variations of the Adapter pattern: The class adapter implements the adaptee's
|
||||||
* the adaptee's interface whereas the object adapter uses composition to
|
* interface whereas the object adapter uses composition to contain the adaptee in the adapter
|
||||||
* contain the adaptee in the adapter object. This example uses the object
|
* object. This example uses the object adapter approach.
|
||||||
* adapter approach.
|
*
|
||||||
* <p>
|
* <p>
|
||||||
* The Adapter ({@link GnomeEngineer}) converts the interface of the target class
|
* The Adapter ({@link BattleFishingBoat}) converts the interface of the adaptee class (
|
||||||
* ({@link GoblinGlider}) into a suitable one expected by the client
|
* {@link FishingBoat}) into a suitable one expected by the client ( {@link BattleShip} ).
|
||||||
* ({@link GnomeEngineeringManager}).
|
*
|
||||||
*
|
* <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 {
|
public class App {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Program entry point
|
* Program entry point.
|
||||||
* @param args command line args
|
*
|
||||||
*/
|
* @param args command line args
|
||||||
public static void main(String[] args) {
|
*/
|
||||||
Engineer manager = new GnomeEngineeringManager();
|
public static void main(String[] args) {
|
||||||
manager.operateDevice();
|
Captain captain = new Captain(new BattleFishingBoat());
|
||||||
}
|
captain.move();
|
||||||
|
captain.fire();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
14
adapter/src/main/java/com/iluwatar/adapter/BattleShip.java
Normal file
14
adapter/src/main/java/com/iluwatar/adapter/BattleShip.java
Normal 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();
|
||||||
|
|
||||||
|
}
|
33
adapter/src/main/java/com/iluwatar/adapter/Captain.java
Normal file
33
adapter/src/main/java/com/iluwatar/adapter/Captain.java
Normal 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,12 +0,0 @@
|
|||||||
package com.iluwatar.adapter;
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* Engineers can operate devices.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public interface Engineer {
|
|
||||||
|
|
||||||
void operateDevice();
|
|
||||||
|
|
||||||
}
|
|
18
adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java
Normal file
18
adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java
Normal 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 ...");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,24 +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();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,20 +0,0 @@
|
|||||||
package com.iluwatar.adapter;
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* GnomeEngineering manager uses {@link Engineer} to operate devices.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class GnomeEngineeringManager implements Engineer {
|
|
||||||
|
|
||||||
private Engineer engineer;
|
|
||||||
|
|
||||||
public GnomeEngineeringManager() {
|
|
||||||
engineer = new GnomeEngineer();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void operateDevice() {
|
|
||||||
engineer.operateDevice();
|
|
||||||
}
|
|
||||||
}
|
|
@ -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!");
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,61 @@
|
|||||||
|
package com.iluwatar.adapter;
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test class
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class AdapterPatternTest {
|
||||||
|
|
||||||
|
private Map<String, Object> beans;
|
||||||
|
|
||||||
|
private static final String BATTLESHIP_BEAN = "engineer";
|
||||||
|
|
||||||
|
private static final String CAPTAIN_BEAN = "captain";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method runs before the test execution and sets the bean objects in the beans Map.
|
||||||
|
*/
|
||||||
|
@Before
|
||||||
|
public void setup() {
|
||||||
|
beans = new HashMap<>();
|
||||||
|
|
||||||
|
BattleFishingBoat battleFishingBoat = spy(new BattleFishingBoat());
|
||||||
|
beans.put(BATTLESHIP_BEAN, battleFishingBoat);
|
||||||
|
|
||||||
|
Captain captain = new Captain();
|
||||||
|
captain.setBattleship((BattleFishingBoat) beans.get(BATTLESHIP_BEAN));
|
||||||
|
beans.put(CAPTAIN_BEAN, captain);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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() {
|
||||||
|
BattleShip captain = (BattleShip) beans.get(CAPTAIN_BEAN);
|
||||||
|
|
||||||
|
// 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();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -1,19 +0,0 @@
|
|||||||
package com.iluwatar.adapter;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import com.iluwatar.adapter.App;
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* Application test
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class AppTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void test() {
|
|
||||||
String[] args = {};
|
|
||||||
App.main(args);
|
|
||||||
}
|
|
||||||
}
|
|
@ -4,7 +4,10 @@ title: Async Method Invocation
|
|||||||
folder: async-method-invocation
|
folder: async-method-invocation
|
||||||
permalink: /patterns/async-method-invocation/
|
permalink: /patterns/async-method-invocation/
|
||||||
categories: Concurrency
|
categories: Concurrency
|
||||||
tags: Java
|
tags:
|
||||||
|
- Java
|
||||||
|
- Difficulty-Intermediate
|
||||||
|
- Functional
|
||||||
---
|
---
|
||||||
|
|
||||||
**Intent:** Asynchronous method invocation is pattern where the calling thread
|
**Intent:** Asynchronous method invocation is pattern where the calling thread
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.iluwatar</groupId>
|
<groupId>com.iluwatar</groupId>
|
||||||
<artifactId>java-design-patterns</artifactId>
|
<artifactId>java-design-patterns</artifactId>
|
||||||
<version>1.7.0</version>
|
<version>1.9.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>async-method-invocation</artifactId>
|
<artifactId>async-method-invocation</artifactId>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -14,5 +14,10 @@
|
|||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mockito</groupId>
|
||||||
|
<artifactId>mockito-core</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</project>
|
</project>
|
||||||
|
@ -5,22 +5,22 @@ import java.util.concurrent.Callable;
|
|||||||
/**
|
/**
|
||||||
* This application demonstrates the async method invocation pattern. Key parts of the pattern are
|
* 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>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>AsyncCallback</code> which can be provided to be executed on task completion and <code>AsyncExecutor</code>
|
||||||
* <code>AsyncExecutor</code> that manages the execution of the async tasks.
|
* that manages the execution of the async tasks.
|
||||||
* <p>
|
* <p>
|
||||||
* The main method shows example flow of async invocations. The main thread starts multiple tasks with
|
* The main method shows example flow of async invocations. The main thread starts multiple tasks with variable
|
||||||
* variable durations and then continues its own work. When the main thread has done it's job it collects
|
* durations and then continues its own work. When the main thread has done it's job it collects the results of the
|
||||||
* the results of the async tasks. Two of the tasks are handled with callbacks, meaning the callbacks are
|
* async tasks. Two of the tasks are handled with callbacks, meaning the callbacks are executed immediately when the
|
||||||
* executed immediately when the tasks complete.
|
* tasks complete.
|
||||||
* <p>
|
* <p>
|
||||||
* Noteworthy difference of thread usage between the async results and callbacks is that the async results
|
* Noteworthy difference of thread usage between the async results and callbacks is that the async results are collected
|
||||||
* are collected in the main thread but the callbacks are executed within the worker threads. This should be
|
* in the main thread but the callbacks are executed within the worker threads. This should be noted when working with
|
||||||
* noted when working with thread pools.
|
* thread pools.
|
||||||
* <p>
|
* <p>
|
||||||
* Java provides its own implementations of async method invocation pattern. FutureTask, CompletableFuture
|
* Java provides its own implementations of async method invocation pattern. FutureTask, CompletableFuture and
|
||||||
* and ExecutorService are the real world implementations of this pattern. But due to the nature of parallel
|
* ExecutorService are the real world implementations of this pattern. But due to the nature of parallel programming,
|
||||||
* programming, the implementations are not trivial. This example does not take all possible scenarios into
|
* the implementations are not trivial. This example does not take all possible scenarios into account but rather
|
||||||
* account but rather provides a simple version that helps to understand the pattern.
|
* provides a simple version that helps to understand the pattern.
|
||||||
*
|
*
|
||||||
* @see AsyncResult
|
* @see AsyncResult
|
||||||
* @see AsyncCallback
|
* @see AsyncCallback
|
||||||
@ -32,66 +32,72 @@ import java.util.concurrent.Callable;
|
|||||||
*/
|
*/
|
||||||
public class App {
|
public class App {
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
/**
|
||||||
// construct a new executor that will run async tasks
|
* Program entry point
|
||||||
AsyncExecutor executor = new ThreadAsyncExecutor();
|
*/
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
// construct a new executor that will run async tasks
|
||||||
|
AsyncExecutor executor = new ThreadAsyncExecutor();
|
||||||
|
|
||||||
// start few async tasks with varying processing times, two last with callback handlers
|
// start few async tasks with varying processing times, two last with callback handlers
|
||||||
AsyncResult<Integer> asyncResult1 = executor.startProcess(lazyval(10, 500));
|
AsyncResult<Integer> asyncResult1 = executor.startProcess(lazyval(10, 500));
|
||||||
AsyncResult<String> asyncResult2 = executor.startProcess(lazyval("test", 300));
|
AsyncResult<String> asyncResult2 = executor.startProcess(lazyval("test", 300));
|
||||||
AsyncResult<Long> asyncResult3 = executor.startProcess(lazyval(50L, 700));
|
AsyncResult<Long> asyncResult3 = executor.startProcess(lazyval(50L, 700));
|
||||||
AsyncResult<Integer> asyncResult4 = executor.startProcess(lazyval(20, 400), callback("Callback result 4"));
|
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<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
|
// 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
|
Thread.sleep(350); // Oh boy I'm working hard here
|
||||||
log("Some hard work done");
|
log("Some hard work done");
|
||||||
|
|
||||||
// wait for completion of the tasks
|
// wait for completion of the tasks
|
||||||
Integer result1 = executor.endProcess(asyncResult1);
|
Integer result1 = executor.endProcess(asyncResult1);
|
||||||
String result2 = executor.endProcess(asyncResult2);
|
String result2 = executor.endProcess(asyncResult2);
|
||||||
Long result3 = executor.endProcess(asyncResult3);
|
Long result3 = executor.endProcess(asyncResult3);
|
||||||
asyncResult4.await();
|
asyncResult4.await();
|
||||||
asyncResult5.await();
|
asyncResult5.await();
|
||||||
|
|
||||||
// log the results of the tasks, callbacks log immediately when complete
|
// log the results of the tasks, callbacks log immediately when complete
|
||||||
log("Result 1: " + result1);
|
log("Result 1: " + result1);
|
||||||
log("Result 2: " + result2);
|
log("Result 2: " + result2);
|
||||||
log("Result 3: " + result3);
|
log("Result 3: " + result3);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a callable that lazily evaluates to given value with artificial delay.
|
* Creates a callable that lazily evaluates to given value with artificial delay.
|
||||||
*
|
*
|
||||||
* @param value value to evaluate
|
* @param value
|
||||||
* @param delayMillis artificial delay in milliseconds
|
* value to evaluate
|
||||||
* @return new callable for lazy evaluation
|
* @param delayMillis
|
||||||
*/
|
* artificial delay in milliseconds
|
||||||
private static <T> Callable<T> lazyval(T value, long delayMillis) {
|
* @return new callable for lazy evaluation
|
||||||
return () -> {
|
*/
|
||||||
Thread.sleep(delayMillis);
|
private static <T> Callable<T> lazyval(T value, long delayMillis) {
|
||||||
log("Task completed with: " + value);
|
return () -> {
|
||||||
return value;
|
Thread.sleep(delayMillis);
|
||||||
};
|
log("Task completed with: " + value);
|
||||||
}
|
return value;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a simple callback that logs the complete status of the async result.
|
* Creates a simple callback that logs the complete status of the async result.
|
||||||
*
|
*
|
||||||
* @param name callback name
|
* @param name
|
||||||
* @return new async callback
|
* callback name
|
||||||
*/
|
* @return new async callback
|
||||||
private static <T> AsyncCallback<T> callback(String name) {
|
*/
|
||||||
return (value, ex) -> {
|
private static <T> AsyncCallback<T> callback(String name) {
|
||||||
if (ex.isPresent()) {
|
return (value, ex) -> {
|
||||||
log(name + " failed: " + ex.map(Exception::getMessage).orElse(""));
|
if (ex.isPresent()) {
|
||||||
} else {
|
log(name + " failed: " + ex.map(Exception::getMessage).orElse(""));
|
||||||
log(name + ": " + value);
|
} else {
|
||||||
}
|
log(name + ": " + value);
|
||||||
};
|
}
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
private static void log(String msg) {
|
private static void log(String msg) {
|
||||||
System.out.println(String.format("[%1$-10s] - %2$s", Thread.currentThread().getName(), msg));
|
System.out.println(String.format("[%1$-10s] - %2$s", Thread.currentThread().getName(), msg));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,12 +11,11 @@ import java.util.Optional;
|
|||||||
*/
|
*/
|
||||||
public interface AsyncCallback<T> {
|
public interface AsyncCallback<T> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Complete handler which is executed when async task is completed or fails execution.
|
* Complete handler which is executed when async task is completed or fails execution.
|
||||||
*
|
*
|
||||||
* @param value the evaluated value from async task, undefined when execution fails
|
* @param value the evaluated value from async task, undefined when execution fails
|
||||||
* @param ex empty value if execution succeeds, some exception if executions fails
|
* @param ex empty value if execution succeeds, some exception if executions fails
|
||||||
*/
|
*/
|
||||||
void onComplete(T value, Optional<Exception> ex);
|
void onComplete(T value, Optional<Exception> ex);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -10,33 +10,32 @@ import java.util.concurrent.ExecutionException;
|
|||||||
*/
|
*/
|
||||||
public interface AsyncExecutor {
|
public interface AsyncExecutor {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Starts processing of an async task. Returns immediately with async result.
|
* Starts processing of an async task. Returns immediately with async result.
|
||||||
*
|
*
|
||||||
* @param task task to be executed asynchronously
|
* @param task task to be executed asynchronously
|
||||||
* @return async result for the task
|
* @return async result for the task
|
||||||
*/
|
*/
|
||||||
<T> AsyncResult<T> startProcess(Callable<T> task);
|
<T> AsyncResult<T> startProcess(Callable<T> task);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Starts processing of an async task. Returns immediately with async result. Executes callback
|
* Starts processing of an async task. Returns immediately with async result. Executes callback
|
||||||
* when the task is completed.
|
* when the task is completed.
|
||||||
*
|
*
|
||||||
* @param task task to be executed asynchronously
|
* @param task task to be executed asynchronously
|
||||||
* @param callback callback to be executed on task completion
|
* @param callback callback to be executed on task completion
|
||||||
* @return async result for the task
|
* @return async result for the task
|
||||||
*/
|
*/
|
||||||
<T> AsyncResult<T> startProcess(Callable<T> task, AsyncCallback<T> callback);
|
<T> AsyncResult<T> startProcess(Callable<T> task, AsyncCallback<T> callback);
|
||||||
|
|
||||||
/**
|
|
||||||
* Ends processing of an async task. Blocks the current thread if necessary and returns the
|
|
||||||
* evaluated value of the completed task.
|
|
||||||
*
|
|
||||||
* @param asyncResult async result of a task
|
|
||||||
* @return evaluated value of the completed task
|
|
||||||
* @throws ExecutionException if execution has failed, containing the root cause
|
|
||||||
* @throws InterruptedException if the execution is interrupted
|
|
||||||
*/
|
|
||||||
<T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException, InterruptedException;
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ends processing of an async task. Blocks the current thread if necessary and returns the
|
||||||
|
* evaluated value of the completed task.
|
||||||
|
*
|
||||||
|
* @param asyncResult async result of a task
|
||||||
|
* @return evaluated value of the completed task
|
||||||
|
* @throws ExecutionException if execution has failed, containing the root cause
|
||||||
|
* @throws InterruptedException if the execution is interrupted
|
||||||
|
*/
|
||||||
|
<T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException, InterruptedException;
|
||||||
}
|
}
|
||||||
|
@ -5,31 +5,29 @@ import java.util.concurrent.ExecutionException;
|
|||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* AsyncResult interface
|
* AsyncResult interface
|
||||||
*
|
|
||||||
* @param <T>
|
|
||||||
*/
|
*/
|
||||||
public interface AsyncResult<T> {
|
public interface AsyncResult<T> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Status of the async task execution.
|
* Status of the async task execution.
|
||||||
*
|
*
|
||||||
* @return <code>true</code> if execution is completed or failed
|
* @return <code>true</code> if execution is completed or failed
|
||||||
*/
|
*/
|
||||||
boolean isCompleted();
|
boolean isCompleted();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the value of completed async task.
|
* Gets the value of completed async task.
|
||||||
*
|
*
|
||||||
* @return evaluated value or throws ExecutionException if execution has failed
|
* @return evaluated value or throws ExecutionException if execution has failed
|
||||||
* @throws ExecutionException if execution has failed, containing the root cause
|
* @throws ExecutionException if execution has failed, containing the root cause
|
||||||
* @throws IllegalStateException if execution is not completed
|
* @throws IllegalStateException if execution is not completed
|
||||||
*/
|
*/
|
||||||
T getValue() throws ExecutionException;
|
T getValue() throws ExecutionException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Blocks the current thread until the async task is completed.
|
* Blocks the current thread until the async task is completed.
|
||||||
*
|
*
|
||||||
* @throws InterruptedException if the execution is interrupted
|
* @throws InterruptedException if the execution is interrupted
|
||||||
*/
|
*/
|
||||||
void await() throws InterruptedException;
|
void await() throws InterruptedException;
|
||||||
}
|
}
|
||||||
|
@ -12,116 +12,117 @@ import java.util.concurrent.atomic.AtomicInteger;
|
|||||||
*/
|
*/
|
||||||
public class ThreadAsyncExecutor implements AsyncExecutor {
|
public class ThreadAsyncExecutor implements AsyncExecutor {
|
||||||
|
|
||||||
/** Index for thread naming */
|
/** Index for thread naming */
|
||||||
private final AtomicInteger idx = new AtomicInteger(0);
|
private final AtomicInteger idx = new AtomicInteger(0);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public <T> AsyncResult<T> startProcess(Callable<T> task) {
|
public <T> AsyncResult<T> startProcess(Callable<T> task) {
|
||||||
return startProcess(task, null);
|
return startProcess(task, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public <T> AsyncResult<T> startProcess(Callable<T> task, AsyncCallback<T> callback) {
|
public <T> AsyncResult<T> startProcess(Callable<T> task, AsyncCallback<T> callback) {
|
||||||
CompletableResult<T> result = new CompletableResult<>(callback);
|
CompletableResult<T> result = new CompletableResult<>(callback);
|
||||||
new Thread(() -> {
|
new Thread(() -> {
|
||||||
try {
|
try {
|
||||||
result.setValue(task.call());
|
result.setValue(task.call());
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
result.setException(ex);
|
result.setException(ex);
|
||||||
}
|
}
|
||||||
}, "executor-" + idx.incrementAndGet()).start();
|
} , "executor-" + idx.incrementAndGet()).start();
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public <T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException, InterruptedException {
|
public <T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException, InterruptedException {
|
||||||
if (asyncResult.isCompleted()) {
|
if (asyncResult.isCompleted()) {
|
||||||
return asyncResult.getValue();
|
return asyncResult.getValue();
|
||||||
} else {
|
} else {
|
||||||
asyncResult.await();
|
asyncResult.await();
|
||||||
return asyncResult.getValue();
|
return asyncResult.getValue();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Simple implementation of async result that allows completing it successfully with a value
|
* Simple implementation of async result that allows completing it successfully with a value or exceptionally with an
|
||||||
* or exceptionally with an exception. A really simplified version from its real life cousins
|
* exception. A really simplified version from its real life cousins FutureTask and CompletableFuture.
|
||||||
* FutureTask and CompletableFuture.
|
*
|
||||||
*
|
* @see java.util.concurrent.FutureTask
|
||||||
* @see java.util.concurrent.FutureTask
|
* @see java.util.concurrent.CompletableFuture
|
||||||
* @see java.util.concurrent.CompletableFuture
|
*/
|
||||||
*/
|
private static class CompletableResult<T> implements AsyncResult<T> {
|
||||||
private static class CompletableResult<T> implements AsyncResult<T> {
|
|
||||||
|
|
||||||
static final int RUNNING = 1;
|
static final int RUNNING = 1;
|
||||||
static final int FAILED = 2;
|
static final int FAILED = 2;
|
||||||
static final int COMPLETED = 3;
|
static final int COMPLETED = 3;
|
||||||
|
|
||||||
final Object lock;
|
final Object lock;
|
||||||
final Optional<AsyncCallback<T>> callback;
|
final Optional<AsyncCallback<T>> callback;
|
||||||
|
|
||||||
volatile int state = RUNNING;
|
volatile int state = RUNNING;
|
||||||
T value;
|
T value;
|
||||||
Exception exception;
|
Exception exception;
|
||||||
|
|
||||||
CompletableResult(AsyncCallback<T> callback) {
|
CompletableResult(AsyncCallback<T> callback) {
|
||||||
this.lock = new Object();
|
this.lock = new Object();
|
||||||
this.callback = Optional.ofNullable(callback);
|
this.callback = Optional.ofNullable(callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the value from successful execution and executes callback if available. Notifies
|
* Sets the value from successful execution and executes callback if available. Notifies any thread waiting for
|
||||||
* any thread waiting for completion.
|
* completion.
|
||||||
*
|
*
|
||||||
* @param value value of the evaluated task
|
* @param value
|
||||||
*/
|
* value of the evaluated task
|
||||||
void setValue(T value) {
|
*/
|
||||||
this.value = value;
|
void setValue(T value) {
|
||||||
this.state = COMPLETED;
|
this.value = value;
|
||||||
this.callback.ifPresent(ac -> ac.onComplete(value, Optional.<Exception>empty()));
|
this.state = COMPLETED;
|
||||||
synchronized (lock) {
|
this.callback.ifPresent(ac -> ac.onComplete(value, Optional.<Exception>empty()));
|
||||||
lock.notifyAll();
|
synchronized (lock) {
|
||||||
}
|
lock.notifyAll();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the exception from failed execution and executes callback if available. Notifies
|
* Sets the exception from failed execution and executes callback if available. Notifies any thread waiting for
|
||||||
* any thread waiting for completion.
|
* completion.
|
||||||
*
|
*
|
||||||
* @param exception exception of the failed task
|
* @param exception
|
||||||
*/
|
* exception of the failed task
|
||||||
void setException(Exception exception) {
|
*/
|
||||||
this.exception = exception;
|
void setException(Exception exception) {
|
||||||
this.state = FAILED;
|
this.exception = exception;
|
||||||
this.callback.ifPresent(ac -> ac.onComplete(null, Optional.of(exception)));
|
this.state = FAILED;
|
||||||
synchronized (lock) {
|
this.callback.ifPresent(ac -> ac.onComplete(null, Optional.of(exception)));
|
||||||
lock.notifyAll();
|
synchronized (lock) {
|
||||||
}
|
lock.notifyAll();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isCompleted() {
|
public boolean isCompleted() {
|
||||||
return (state > RUNNING);
|
return state > RUNNING;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public T getValue() throws ExecutionException {
|
public T getValue() throws ExecutionException {
|
||||||
if (state == COMPLETED) {
|
if (state == COMPLETED) {
|
||||||
return value;
|
return value;
|
||||||
} else if (state == FAILED) {
|
} else if (state == FAILED) {
|
||||||
throw new ExecutionException(exception);
|
throw new ExecutionException(exception);
|
||||||
} else {
|
} else {
|
||||||
throw new IllegalStateException("Execution not completed yet");
|
throw new IllegalStateException("Execution not completed yet");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void await() throws InterruptedException {
|
public void await() throws InterruptedException {
|
||||||
synchronized (lock) {
|
synchronized (lock) {
|
||||||
if (!isCompleted()) {
|
if (!isCompleted()) {
|
||||||
lock.wait();
|
lock.wait();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,10 +9,9 @@ import org.junit.Test;
|
|||||||
*/
|
*/
|
||||||
public class AppTest {
|
public class AppTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void test() throws Exception {
|
public void test() throws Exception {
|
||||||
String[] args = {};
|
String[] args = {};
|
||||||
App.main(args);
|
App.main(args);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -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());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -7,8 +7,11 @@ categories: Structural
|
|||||||
tags:
|
tags:
|
||||||
- Java
|
- Java
|
||||||
- Gang Of Four
|
- Gang Of Four
|
||||||
|
- Difficulty-Intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
|
**Also known as:** Handle/Body
|
||||||
|
|
||||||
**Intent:** Decouple an abstraction from its implementation so that the two can
|
**Intent:** Decouple an abstraction from its implementation so that the two can
|
||||||
vary independently.
|
vary independently.
|
||||||
|
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.iluwatar</groupId>
|
<groupId>com.iluwatar</groupId>
|
||||||
<artifactId>java-design-patterns</artifactId>
|
<artifactId>java-design-patterns</artifactId>
|
||||||
<version>1.7.0</version>
|
<version>1.9.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>bridge</artifactId>
|
<artifactId>bridge</artifactId>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -14,5 +14,10 @@
|
|||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mockito</groupId>
|
||||||
|
<artifactId>mockito-core</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</project>
|
</project>
|
||||||
|
@ -2,41 +2,38 @@ package com.iluwatar.bridge;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* The Bridge pattern can also be thought of as two layers of abstraction. With Bridge,
|
* The Bridge pattern can also be thought of as two layers of abstraction. With Bridge, you can
|
||||||
* you can decouple an abstraction from its implementation so that the two can vary independently.
|
* decouple an abstraction from its implementation so that the two can vary independently.
|
||||||
* <p>
|
* <p>
|
||||||
* In Bridge pattern both abstraction ({@link MagicWeapon}) and implementation
|
* In Bridge pattern both abstraction ({@link MagicWeapon}) and implementation (
|
||||||
* ({@link MagicWeaponImpl}) have their own class hierarchies. The interface of the
|
* {@link MagicWeaponImpl}) have their own class hierarchies. The interface of the implementations
|
||||||
* implementations can be changed without affecting the clients.
|
* can be changed without affecting the clients.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class App {
|
public class App {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Program entry point
|
* Program entry point
|
||||||
* @param args command line args
|
*
|
||||||
*/
|
* @param args command line args
|
||||||
public static void main(String[] args) {
|
*/
|
||||||
BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(
|
public static void main(String[] args) {
|
||||||
new Excalibur());
|
BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(new Excalibur());
|
||||||
blindingMagicWeapon.wield();
|
blindingMagicWeapon.wield();
|
||||||
blindingMagicWeapon.blind();
|
blindingMagicWeapon.blind();
|
||||||
blindingMagicWeapon.swing();
|
blindingMagicWeapon.swing();
|
||||||
blindingMagicWeapon.unwield();
|
blindingMagicWeapon.unwield();
|
||||||
|
|
||||||
FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(
|
FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(new Mjollnir());
|
||||||
new Mjollnir());
|
flyingMagicWeapon.wield();
|
||||||
flyingMagicWeapon.wield();
|
flyingMagicWeapon.fly();
|
||||||
flyingMagicWeapon.fly();
|
flyingMagicWeapon.swing();
|
||||||
flyingMagicWeapon.swing();
|
flyingMagicWeapon.unwield();
|
||||||
flyingMagicWeapon.unwield();
|
|
||||||
|
|
||||||
SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(
|
SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(new Stormbringer());
|
||||||
new Stormbringer());
|
soulEatingMagicWeapon.wield();
|
||||||
soulEatingMagicWeapon.wield();
|
soulEatingMagicWeapon.swing();
|
||||||
soulEatingMagicWeapon.swing();
|
soulEatingMagicWeapon.eatSoul();
|
||||||
soulEatingMagicWeapon.eatSoul();
|
soulEatingMagicWeapon.unwield();
|
||||||
soulEatingMagicWeapon.unwield();
|
}
|
||||||
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -7,32 +7,31 @@ package com.iluwatar.bridge;
|
|||||||
*/
|
*/
|
||||||
public class BlindingMagicWeapon extends MagicWeapon {
|
public class BlindingMagicWeapon extends MagicWeapon {
|
||||||
|
|
||||||
public BlindingMagicWeapon(BlindingMagicWeaponImpl imp) {
|
public BlindingMagicWeapon(BlindingMagicWeaponImpl imp) {
|
||||||
super(imp);
|
super(imp);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public BlindingMagicWeaponImpl getImp() {
|
public BlindingMagicWeaponImpl getImp() {
|
||||||
return (BlindingMagicWeaponImpl) imp;
|
return (BlindingMagicWeaponImpl) imp;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void wield() {
|
public void wield() {
|
||||||
getImp().wieldImp();
|
getImp().wieldImp();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void swing() {
|
public void swing() {
|
||||||
getImp().swingImp();
|
getImp().swingImp();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void unwield() {
|
public void unwield() {
|
||||||
getImp().unwieldImp();
|
getImp().unwieldImp();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void blind() {
|
|
||||||
getImp().blindImp();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
public void blind() {
|
||||||
|
getImp().blindImp();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,6 @@ package com.iluwatar.bridge;
|
|||||||
*/
|
*/
|
||||||
public abstract class BlindingMagicWeaponImpl extends MagicWeaponImpl {
|
public abstract class BlindingMagicWeaponImpl extends MagicWeaponImpl {
|
||||||
|
|
||||||
public abstract void blindImp();
|
public abstract void blindImp();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -7,25 +7,23 @@ package com.iluwatar.bridge;
|
|||||||
*/
|
*/
|
||||||
public class Excalibur extends BlindingMagicWeaponImpl {
|
public class Excalibur extends BlindingMagicWeaponImpl {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void wieldImp() {
|
public void wieldImp() {
|
||||||
System.out.println("wielding Excalibur");
|
System.out.println("wielding Excalibur");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void swingImp() {
|
public void swingImp() {
|
||||||
System.out.println("swinging Excalibur");
|
System.out.println("swinging Excalibur");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void unwieldImp() {
|
public void unwieldImp() {
|
||||||
System.out.println("unwielding Excalibur");
|
System.out.println("unwielding Excalibur");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void blindImp() {
|
|
||||||
System.out
|
|
||||||
.println("bright light streams from Excalibur blinding the enemy");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void blindImp() {
|
||||||
|
System.out.println("bright light streams from Excalibur blinding the enemy");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,31 +7,31 @@ package com.iluwatar.bridge;
|
|||||||
*/
|
*/
|
||||||
public class FlyingMagicWeapon extends MagicWeapon {
|
public class FlyingMagicWeapon extends MagicWeapon {
|
||||||
|
|
||||||
public FlyingMagicWeapon(FlyingMagicWeaponImpl imp) {
|
public FlyingMagicWeapon(FlyingMagicWeaponImpl imp) {
|
||||||
super(imp);
|
super(imp);
|
||||||
}
|
}
|
||||||
|
|
||||||
public FlyingMagicWeaponImpl getImp() {
|
public FlyingMagicWeaponImpl getImp() {
|
||||||
return (FlyingMagicWeaponImpl) imp;
|
return (FlyingMagicWeaponImpl) imp;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void wield() {
|
public void wield() {
|
||||||
getImp().wieldImp();
|
getImp().wieldImp();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void swing() {
|
public void swing() {
|
||||||
getImp().swingImp();
|
getImp().swingImp();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void unwield() {
|
public void unwield() {
|
||||||
getImp().unwieldImp();
|
getImp().unwieldImp();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void fly() {
|
public void fly() {
|
||||||
getImp().flyImp();
|
getImp().flyImp();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,6 @@ package com.iluwatar.bridge;
|
|||||||
*/
|
*/
|
||||||
public abstract class FlyingMagicWeaponImpl extends MagicWeaponImpl {
|
public abstract class FlyingMagicWeaponImpl extends MagicWeaponImpl {
|
||||||
|
|
||||||
public abstract void flyImp();
|
public abstract void flyImp();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -7,20 +7,19 @@ package com.iluwatar.bridge;
|
|||||||
*/
|
*/
|
||||||
public abstract class MagicWeapon {
|
public abstract class MagicWeapon {
|
||||||
|
|
||||||
protected MagicWeaponImpl imp;
|
protected MagicWeaponImpl imp;
|
||||||
|
|
||||||
public MagicWeapon(MagicWeaponImpl imp) {
|
public MagicWeapon(MagicWeaponImpl imp) {
|
||||||
this.imp = imp;
|
this.imp = imp;
|
||||||
}
|
}
|
||||||
|
|
||||||
public abstract void wield();
|
public abstract void wield();
|
||||||
|
|
||||||
public abstract void swing();
|
public abstract void swing();
|
||||||
|
|
||||||
public abstract void unwield();
|
public abstract void unwield();
|
||||||
|
|
||||||
public MagicWeaponImpl getImp() {
|
|
||||||
return imp;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
public MagicWeaponImpl getImp() {
|
||||||
|
return imp;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,10 +7,10 @@ package com.iluwatar.bridge;
|
|||||||
*/
|
*/
|
||||||
public abstract class MagicWeaponImpl {
|
public abstract class MagicWeaponImpl {
|
||||||
|
|
||||||
public abstract void wieldImp();
|
public abstract void wieldImp();
|
||||||
|
|
||||||
public abstract void swingImp();
|
public abstract void swingImp();
|
||||||
|
|
||||||
public abstract void unwieldImp();
|
public abstract void unwieldImp();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -7,25 +7,23 @@ package com.iluwatar.bridge;
|
|||||||
*/
|
*/
|
||||||
public class Mjollnir extends FlyingMagicWeaponImpl {
|
public class Mjollnir extends FlyingMagicWeaponImpl {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void wieldImp() {
|
public void wieldImp() {
|
||||||
System.out.println("wielding Mjollnir");
|
System.out.println("wielding Mjollnir");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void swingImp() {
|
public void swingImp() {
|
||||||
System.out.println("swinging Mjollnir");
|
System.out.println("swinging Mjollnir");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void unwieldImp() {
|
public void unwieldImp() {
|
||||||
System.out.println("unwielding Mjollnir");
|
System.out.println("unwielding Mjollnir");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void flyImp() {
|
|
||||||
System.out
|
|
||||||
.println("Mjollnir hits the enemy in the air and returns back to the owner's hand");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void flyImp() {
|
||||||
|
System.out.println("Mjollnir hits the enemy in the air and returns back to the owner's hand");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,32 +7,32 @@ package com.iluwatar.bridge;
|
|||||||
*/
|
*/
|
||||||
public class SoulEatingMagicWeapon extends MagicWeapon {
|
public class SoulEatingMagicWeapon extends MagicWeapon {
|
||||||
|
|
||||||
public SoulEatingMagicWeapon(SoulEatingMagicWeaponImpl imp) {
|
public SoulEatingMagicWeapon(SoulEatingMagicWeaponImpl imp) {
|
||||||
super(imp);
|
super(imp);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SoulEatingMagicWeaponImpl getImp() {
|
public SoulEatingMagicWeaponImpl getImp() {
|
||||||
return (SoulEatingMagicWeaponImpl) imp;
|
return (SoulEatingMagicWeaponImpl) imp;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void wield() {
|
public void wield() {
|
||||||
getImp().wieldImp();
|
getImp().wieldImp();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void swing() {
|
public void swing() {
|
||||||
getImp().swingImp();
|
getImp().swingImp();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void unwield() {
|
public void unwield() {
|
||||||
getImp().unwieldImp();
|
getImp().unwieldImp();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void eatSoul() {
|
public void eatSoul() {
|
||||||
getImp().eatSoulImp();
|
getImp().eatSoulImp();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,6 @@ package com.iluwatar.bridge;
|
|||||||
*/
|
*/
|
||||||
public abstract class SoulEatingMagicWeaponImpl extends MagicWeaponImpl {
|
public abstract class SoulEatingMagicWeaponImpl extends MagicWeaponImpl {
|
||||||
|
|
||||||
public abstract void eatSoulImp();
|
public abstract void eatSoulImp();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -7,24 +7,23 @@ package com.iluwatar.bridge;
|
|||||||
*/
|
*/
|
||||||
public class Stormbringer extends SoulEatingMagicWeaponImpl {
|
public class Stormbringer extends SoulEatingMagicWeaponImpl {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void wieldImp() {
|
public void wieldImp() {
|
||||||
System.out.println("wielding Stormbringer");
|
System.out.println("wielding Stormbringer");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void swingImp() {
|
public void swingImp() {
|
||||||
System.out.println("swinging Stormbringer");
|
System.out.println("swinging Stormbringer");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void unwieldImp() {
|
public void unwieldImp() {
|
||||||
System.out.println("unwielding Stormbringer");
|
System.out.println("unwielding Stormbringer");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void eatSoulImp() {
|
|
||||||
System.out.println("Stormbringer devours the enemy's soul");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void eatSoulImp() {
|
||||||
|
System.out.println("Stormbringer devours the enemy's soul");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,8 +2,6 @@ package com.iluwatar.bridge;
|
|||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import com.iluwatar.bridge.App;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* Application test
|
* Application test
|
||||||
@ -11,9 +9,9 @@ import com.iluwatar.bridge.App;
|
|||||||
*/
|
*/
|
||||||
public class AppTest {
|
public class AppTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void test() {
|
public void test() {
|
||||||
String[] args = {};
|
String[] args = {};
|
||||||
App.main(args);
|
App.main(args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -7,6 +7,7 @@ categories: Creational
|
|||||||
tags:
|
tags:
|
||||||
- Java
|
- Java
|
||||||
- Gang Of Four
|
- Gang Of Four
|
||||||
|
- Difficulty-Intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
**Intent:** Separate the construction of a complex object from its
|
**Intent:** Separate the construction of a complex object from its
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.iluwatar</groupId>
|
<groupId>com.iluwatar</groupId>
|
||||||
<artifactId>java-design-patterns</artifactId>
|
<artifactId>java-design-patterns</artifactId>
|
||||||
<version>1.7.0</version>
|
<version>1.9.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>builder</artifactId>
|
<artifactId>builder</artifactId>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -1,55 +1,55 @@
|
|||||||
package com.iluwatar.builder;
|
package com.iluwatar.builder;
|
||||||
|
|
||||||
import com.iluwatar. builder.Hero.HeroBuilder;
|
import com.iluwatar.builder.Hero.HeroBuilder;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* The intention of the Builder pattern is to find a solution to the telescoping
|
* The intention of the Builder pattern is to find a solution to the telescoping constructor
|
||||||
* constructor anti-pattern. The telescoping constructor anti-pattern occurs when the
|
* anti-pattern. The telescoping constructor anti-pattern occurs when the increase of object
|
||||||
* increase of object constructor parameter combination leads to an exponential list
|
* constructor parameter combination leads to an exponential list of constructors. Instead of using
|
||||||
* of constructors. Instead of using numerous constructors, the builder pattern uses
|
* numerous constructors, the builder pattern uses another object, a builder, that receives each
|
||||||
* another object, a builder, that receives each initialization parameter step by step
|
* initialization parameter step by step and then returns the resulting constructed object at once.
|
||||||
* and then returns the resulting constructed object at once.
|
|
||||||
* <p>
|
* <p>
|
||||||
* The Builder pattern has another benefit. It can be used for objects that contain
|
* The Builder pattern has another benefit. It can be used for objects that contain flat data (html
|
||||||
* flat data (html code, SQL query, X.509 certificate...), that is to say, data that
|
* code, SQL query, X.509 certificate...), that is to say, data that can't be easily edited. This
|
||||||
* can't be easily edited. This type of data cannot be edited step by step and must
|
* type of data cannot be edited step by step and must be edited at once. The best way to construct
|
||||||
* be edited at once. The best way to construct such an object is to use a builder
|
* such an object is to use a builder class.
|
||||||
* class.
|
|
||||||
* <p>
|
* <p>
|
||||||
* In this example we have the Builder pattern variation as described by Joshua Bloch in
|
* In this example we have the Builder pattern variation as described by Joshua Bloch in Effective
|
||||||
* Effective Java 2nd Edition.
|
* Java 2nd Edition.
|
||||||
* <p>
|
* <p>
|
||||||
* We want to build {@link Hero} objects, but its construction is complex because of the
|
* We want to build {@link Hero} objects, but its construction is complex because of the many
|
||||||
* many parameters needed. To aid the user we introduce {@link HeroBuilder} class.
|
* parameters needed. To aid the user we introduce {@link HeroBuilder} class. {@link HeroBuilder}
|
||||||
* {@link HeroBuilder} takes the minimum parameters to build {@link Hero} object in its
|
* takes the minimum parameters to build {@link Hero} object in its constructor. After that
|
||||||
* constructor. After that additional configuration for the {@link Hero} object can be
|
* additional configuration for the {@link Hero} object can be done using the fluent
|
||||||
* done using the fluent {@link HeroBuilder} interface. When configuration is ready the
|
* {@link HeroBuilder} interface. When configuration is ready the build method is called to receive
|
||||||
* build method is called to receive the final {@link Hero} object.
|
* the final {@link Hero} object.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class App {
|
public class App {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Program entry point
|
* Program entry point
|
||||||
* @param args command line args
|
*
|
||||||
*/
|
* @param args command line args
|
||||||
public static void main(String[] args) {
|
*/
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
Hero mage = new HeroBuilder(Profession.MAGE, "Riobard")
|
Hero mage =
|
||||||
.withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER)
|
new HeroBuilder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK)
|
||||||
.build();
|
.withWeapon(Weapon.DAGGER).build();
|
||||||
System.out.println(mage);
|
System.out.println(mage);
|
||||||
|
|
||||||
Hero warrior = new HeroBuilder(Profession.WARRIOR, "Amberjill")
|
Hero warrior =
|
||||||
.withHairColor(HairColor.BLOND)
|
new HeroBuilder(Profession.WARRIOR, "Amberjill").withHairColor(HairColor.BLOND)
|
||||||
.withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL)
|
.withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD)
|
||||||
.withWeapon(Weapon.SWORD).build();
|
.build();
|
||||||
System.out.println(warrior);
|
System.out.println(warrior);
|
||||||
|
|
||||||
Hero thief = new HeroBuilder(Profession.THIEF, "Desmond")
|
Hero thief =
|
||||||
.withHairType(HairType.BALD).withWeapon(Weapon.BOW).build();
|
new HeroBuilder(Profession.THIEF, "Desmond").withHairType(HairType.BALD)
|
||||||
System.out.println(thief);
|
.withWeapon(Weapon.BOW).build();
|
||||||
|
System.out.println(thief);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,16 +7,16 @@ package com.iluwatar.builder;
|
|||||||
*/
|
*/
|
||||||
public enum Armor {
|
public enum Armor {
|
||||||
|
|
||||||
CLOTHES("clothes"), LEATHER("leather"), CHAIN_MAIL("chain mail"), PLATE_MAIL("plate mail");
|
CLOTHES("clothes"), LEATHER("leather"), CHAIN_MAIL("chain mail"), PLATE_MAIL("plate mail");
|
||||||
|
|
||||||
private String title;
|
private String title;
|
||||||
|
|
||||||
Armor(String title) {
|
Armor(String title) {
|
||||||
this.title = title;
|
this.title = title;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return title;
|
return title;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,11 +7,11 @@ package com.iluwatar.builder;
|
|||||||
*/
|
*/
|
||||||
public enum HairColor {
|
public enum HairColor {
|
||||||
|
|
||||||
WHITE, BLOND, RED, BROWN, BLACK;
|
WHITE, BLOND, RED, BROWN, BLACK;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return name().toLowerCase();
|
return name().toLowerCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -7,16 +7,17 @@ package com.iluwatar.builder;
|
|||||||
*/
|
*/
|
||||||
public enum HairType {
|
public enum HairType {
|
||||||
|
|
||||||
BALD("bald"), SHORT("short"), CURLY("curly"), LONG_STRAIGHT("long straight"), LONG_CURLY("long curly");
|
BALD("bald"), SHORT("short"), CURLY("curly"), LONG_STRAIGHT("long straight"), LONG_CURLY(
|
||||||
|
"long curly");
|
||||||
|
|
||||||
private String title;
|
private String title;
|
||||||
|
|
||||||
HairType(String title) {
|
HairType(String title) {
|
||||||
this.title = title;
|
this.title = title;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return title;
|
return title;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,123 +7,125 @@ package com.iluwatar.builder;
|
|||||||
*/
|
*/
|
||||||
public class Hero {
|
public class Hero {
|
||||||
|
|
||||||
private final Profession profession;
|
private final Profession profession;
|
||||||
private final String name;
|
private final String name;
|
||||||
private final HairType hairType;
|
private final HairType hairType;
|
||||||
private final HairColor hairColor;
|
private final HairColor hairColor;
|
||||||
private final Armor armor;
|
private final Armor armor;
|
||||||
private final Weapon weapon;
|
private final Weapon weapon;
|
||||||
|
|
||||||
public Profession getProfession() {
|
public Profession getProfession() {
|
||||||
return profession;
|
return profession;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public HairType getHairType() {
|
public HairType getHairType() {
|
||||||
return hairType;
|
return hairType;
|
||||||
}
|
}
|
||||||
|
|
||||||
public HairColor getHairColor() {
|
public HairColor getHairColor() {
|
||||||
return hairColor;
|
return hairColor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Armor getArmor() {
|
public Armor getArmor() {
|
||||||
return armor;
|
return armor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Weapon getWeapon() {
|
public Weapon getWeapon() {
|
||||||
return weapon;
|
return weapon;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
|
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
sb.append("This is a ");
|
sb.append("This is a ");
|
||||||
sb.append(profession);
|
sb.append(profession);
|
||||||
sb.append(" named ");
|
sb.append(" named ");
|
||||||
sb.append(name);
|
sb.append(name);
|
||||||
if (hairColor != null || hairType != null) {
|
if (hairColor != null || hairType != null) {
|
||||||
sb.append(" with ");
|
sb.append(" with ");
|
||||||
if (hairColor != null) {
|
if (hairColor != null) {
|
||||||
sb.append(hairColor);
|
sb.append(hairColor);
|
||||||
sb.append(" ");
|
sb.append(" ");
|
||||||
}
|
}
|
||||||
if (hairType != null) {
|
if (hairType != null) {
|
||||||
sb.append(hairType);
|
sb.append(hairType);
|
||||||
sb.append(" ");
|
sb.append(" ");
|
||||||
}
|
}
|
||||||
sb.append(hairType != HairType.BALD ? "hair" : "head");
|
sb.append(hairType != HairType.BALD ? "hair" : "head");
|
||||||
}
|
}
|
||||||
if (armor != null) {
|
if (armor != null) {
|
||||||
sb.append(" wearing ");
|
sb.append(" wearing ");
|
||||||
sb.append(armor);
|
sb.append(armor);
|
||||||
}
|
}
|
||||||
if (weapon != null) {
|
if (weapon != null) {
|
||||||
sb.append(" and wielding a ");
|
sb.append(" and wielding a ");
|
||||||
sb.append(weapon);
|
sb.append(weapon);
|
||||||
}
|
}
|
||||||
sb.append(".");
|
sb.append(".");
|
||||||
return sb.toString();
|
return sb.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
private Hero(HeroBuilder builder) {
|
private Hero(HeroBuilder builder) {
|
||||||
this.profession = builder.profession;
|
this.profession = builder.profession;
|
||||||
this.name = builder.name;
|
this.name = builder.name;
|
||||||
this.hairColor = builder.hairColor;
|
this.hairColor = builder.hairColor;
|
||||||
this.hairType = builder.hairType;
|
this.hairType = builder.hairType;
|
||||||
this.weapon = builder.weapon;
|
this.weapon = builder.weapon;
|
||||||
this.armor = builder.armor;
|
this.armor = builder.armor;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* The builder class.
|
* The builder class.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public static class HeroBuilder {
|
public static class HeroBuilder {
|
||||||
|
|
||||||
private final Profession profession;
|
private final Profession profession;
|
||||||
private final String name;
|
private final String name;
|
||||||
private HairType hairType;
|
private HairType hairType;
|
||||||
private HairColor hairColor;
|
private HairColor hairColor;
|
||||||
private Armor armor;
|
private Armor armor;
|
||||||
private Weapon weapon;
|
private Weapon weapon;
|
||||||
|
|
||||||
public HeroBuilder(Profession profession, String name) {
|
/**
|
||||||
if (profession == null || name == null) {
|
* Constructor
|
||||||
throw new IllegalArgumentException(
|
*/
|
||||||
"profession and name can not be null");
|
public HeroBuilder(Profession profession, String name) {
|
||||||
}
|
if (profession == null || name == null) {
|
||||||
this.profession = profession;
|
throw new IllegalArgumentException("profession and name can not be null");
|
||||||
this.name = name;
|
}
|
||||||
}
|
this.profession = profession;
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
public HeroBuilder withHairType(HairType hairType) {
|
public HeroBuilder withHairType(HairType hairType) {
|
||||||
this.hairType = hairType;
|
this.hairType = hairType;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public HeroBuilder withHairColor(HairColor hairColor) {
|
public HeroBuilder withHairColor(HairColor hairColor) {
|
||||||
this.hairColor = hairColor;
|
this.hairColor = hairColor;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public HeroBuilder withArmor(Armor armor) {
|
public HeroBuilder withArmor(Armor armor) {
|
||||||
this.armor = armor;
|
this.armor = armor;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public HeroBuilder withWeapon(Weapon weapon) {
|
public HeroBuilder withWeapon(Weapon weapon) {
|
||||||
this.weapon = weapon;
|
this.weapon = weapon;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Hero build() {
|
public Hero build() {
|
||||||
return new Hero(this);
|
return new Hero(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,11 +7,10 @@ package com.iluwatar.builder;
|
|||||||
*/
|
*/
|
||||||
public enum Profession {
|
public enum Profession {
|
||||||
|
|
||||||
WARRIOR, THIEF, MAGE, PRIEST;
|
WARRIOR, THIEF, MAGE, PRIEST;
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return name().toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return name().toLowerCase();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,11 +7,10 @@ package com.iluwatar.builder;
|
|||||||
*/
|
*/
|
||||||
public enum Weapon {
|
public enum Weapon {
|
||||||
|
|
||||||
DAGGER, SWORD, AXE, WARHAMMER, BOW;
|
DAGGER, SWORD, AXE, WARHAMMER, BOW;
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return name().toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return name().toLowerCase();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,8 +2,6 @@ package com.iluwatar.builder;
|
|||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import com.iluwatar. builder.App;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* Application test
|
* Application test
|
||||||
@ -11,9 +9,9 @@ import com.iluwatar. builder.App;
|
|||||||
*/
|
*/
|
||||||
public class AppTest {
|
public class AppTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void test() {
|
public void test() {
|
||||||
String[] args = {};
|
String[] args = {};
|
||||||
App.main(args);
|
App.main(args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
56
builder/src/test/java/com/iluwatar/builder/HeroTest.java
Normal file
56
builder/src/test/java/com/iluwatar/builder/HeroTest.java
Normal 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());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -4,7 +4,9 @@ title: Business Delegate
|
|||||||
folder: business-delegate
|
folder: business-delegate
|
||||||
permalink: /patterns/business-delegate/
|
permalink: /patterns/business-delegate/
|
||||||
categories: Business Tier
|
categories: Business Tier
|
||||||
tags: Java
|
tags:
|
||||||
|
- Java
|
||||||
|
- Difficulty-Intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
**Intent:** The Business Delegate pattern adds an abstraction layer between
|
**Intent:** The Business Delegate pattern adds an abstraction layer between
|
||||||
|
@ -6,7 +6,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.iluwatar</groupId>
|
<groupId>com.iluwatar</groupId>
|
||||||
<artifactId>java-design-patterns</artifactId>
|
<artifactId>java-design-patterns</artifactId>
|
||||||
<version>1.7.0</version>
|
<version>1.9.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>business-delegate</artifactId>
|
<artifactId>business-delegate</artifactId>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -15,5 +15,10 @@
|
|||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mockito</groupId>
|
||||||
|
<artifactId>mockito-core</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</project>
|
</project>
|
||||||
|
@ -1,35 +1,40 @@
|
|||||||
package com.iluwatar.business.delegate;
|
package com.iluwatar.business.delegate;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* The Business Delegate pattern adds an abstraction layer between the presentation and business
|
||||||
|
* tiers. By using the pattern we gain loose coupling between the tiers. The Business Delegate
|
||||||
|
* encapsulates knowledge about how to locate, connect to, and interact with the business objects
|
||||||
|
* that make up the application.
|
||||||
*
|
*
|
||||||
* The Business Delegate pattern adds an abstraction layer between the presentation and business tiers.
|
* <p>Some of the services the Business Delegate uses are instantiated directly, and some can be
|
||||||
* By using the pattern we gain loose coupling between the tiers. The Business Delegate encapsulates
|
* retrieved through service lookups. The Business Delegate itself may contain business logic too
|
||||||
* knowledge about how to locate, connect to, and interact with the business objects that make up
|
* potentially tying together multiple service calls, exception handling, retrying etc.
|
||||||
* the application.
|
*
|
||||||
* <p>
|
* <p>In this example the client ({@link Client}) utilizes a business delegate (
|
||||||
* Some of the services the Business Delegate uses are instantiated directly, and some can be retrieved
|
* {@link BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate
|
||||||
* through service lookups. The Business Delegate itself may contain business logic too potentially tying
|
* service and makes the service call.
|
||||||
* together multiple service calls, exception handling, retrying etc.
|
|
||||||
* <p>
|
|
||||||
* In this example the client ({@link Client}) utilizes a business delegate ({@link BusinessDelegate}) to execute a task.
|
|
||||||
* The Business Delegate then selects the appropriate service and makes the service call.
|
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class App {
|
public class App {
|
||||||
|
|
||||||
/**
|
|
||||||
* Program entry point
|
|
||||||
* @param args command line args
|
|
||||||
*/
|
|
||||||
public static void main(String[] args) {
|
|
||||||
|
|
||||||
BusinessDelegate businessDelegate = new BusinessDelegate();
|
|
||||||
businessDelegate.setServiceType(ServiceType.EJB);
|
|
||||||
|
|
||||||
Client client = new Client(businessDelegate);
|
/**
|
||||||
client.doTask();
|
* Program entry point.
|
||||||
|
*
|
||||||
|
* @param args command line args
|
||||||
|
*/
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
businessDelegate.setServiceType(ServiceType.JMS);
|
BusinessDelegate businessDelegate = new BusinessDelegate();
|
||||||
client.doTask();
|
BusinessLookup businessLookup = new BusinessLookup();
|
||||||
}
|
businessLookup.setEjbService(new EjbService());
|
||||||
|
businessLookup.setJmsService(new JmsService());
|
||||||
|
|
||||||
|
businessDelegate.setLookupService(businessLookup);
|
||||||
|
businessDelegate.setServiceType(ServiceType.EJB);
|
||||||
|
|
||||||
|
Client client = new Client(businessDelegate);
|
||||||
|
client.doTask();
|
||||||
|
|
||||||
|
businessDelegate.setServiceType(ServiceType.JMS);
|
||||||
|
client.doTask();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,22 +1,24 @@
|
|||||||
package com.iluwatar.business.delegate;
|
package com.iluwatar.business.delegate;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
|
||||||
* BusinessDelegate separates the presentation and business tiers
|
* BusinessDelegate separates the presentation and business tiers
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class BusinessDelegate {
|
public class BusinessDelegate {
|
||||||
|
|
||||||
private BusinessLookup lookupService = new BusinessLookup();
|
|
||||||
private BusinessService businessService;
|
|
||||||
private ServiceType serviceType;
|
|
||||||
|
|
||||||
public void setServiceType(ServiceType serviceType) {
|
private BusinessLookup lookupService;
|
||||||
this.serviceType = serviceType;
|
private BusinessService businessService;
|
||||||
}
|
private ServiceType serviceType;
|
||||||
|
|
||||||
public void doTask() {
|
public void setLookupService(BusinessLookup businessLookup) {
|
||||||
businessService = lookupService.getBusinessService(serviceType);
|
this.lookupService = businessLookup;
|
||||||
businessService.doProcessing();
|
}
|
||||||
}
|
|
||||||
|
public void setServiceType(ServiceType serviceType) {
|
||||||
|
this.serviceType = serviceType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void doTask() {
|
||||||
|
businessService = lookupService.getBusinessService(serviceType);
|
||||||
|
businessService.doProcessing();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,17 +1,31 @@
|
|||||||
package com.iluwatar.business.delegate;
|
package com.iluwatar.business.delegate;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
* Class for performing service lookups.
|
||||||
* Class for performing service lookups
|
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class BusinessLookup {
|
public class BusinessLookup {
|
||||||
|
|
||||||
public BusinessService getBusinessService(ServiceType serviceType) {
|
private EjbService ejbService;
|
||||||
if (serviceType.equals(ServiceType.EJB)) {
|
|
||||||
return new EjbService();
|
private JmsService jmsService;
|
||||||
} else {
|
|
||||||
return new JmsService();
|
/**
|
||||||
}
|
* @param serviceType Type of service instance to be returned.
|
||||||
}
|
* @return Service instance.
|
||||||
|
*/
|
||||||
|
public BusinessService getBusinessService(ServiceType serviceType) {
|
||||||
|
if (serviceType.equals(ServiceType.EJB)) {
|
||||||
|
return ejbService;
|
||||||
|
} else {
|
||||||
|
return jmsService;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setJmsService(JmsService jmsService) {
|
||||||
|
this.jmsService = jmsService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEjbService(EjbService ejbService) {
|
||||||
|
this.ejbService = ejbService;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,5 +7,5 @@ package com.iluwatar.business.delegate;
|
|||||||
*/
|
*/
|
||||||
public interface BusinessService {
|
public interface BusinessService {
|
||||||
|
|
||||||
void doProcessing();
|
void doProcessing();
|
||||||
}
|
}
|
||||||
|
@ -7,13 +7,13 @@ package com.iluwatar.business.delegate;
|
|||||||
*/
|
*/
|
||||||
public class Client {
|
public class Client {
|
||||||
|
|
||||||
private BusinessDelegate businessDelegate;
|
private BusinessDelegate businessDelegate;
|
||||||
|
|
||||||
public Client(BusinessDelegate businessDelegate) {
|
public Client(BusinessDelegate businessDelegate) {
|
||||||
this.businessDelegate = businessDelegate;
|
this.businessDelegate = businessDelegate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void doTask() {
|
public void doTask() {
|
||||||
businessDelegate.doTask();
|
businessDelegate.doTask();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,8 +7,8 @@ package com.iluwatar.business.delegate;
|
|||||||
*/
|
*/
|
||||||
public class EjbService implements BusinessService {
|
public class EjbService implements BusinessService {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void doProcessing() {
|
public void doProcessing() {
|
||||||
System.out.println("EjbService is now processing");
|
System.out.println("EjbService is now processing");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,8 +7,8 @@ package com.iluwatar.business.delegate;
|
|||||||
*/
|
*/
|
||||||
public class JmsService implements BusinessService {
|
public class JmsService implements BusinessService {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void doProcessing() {
|
public void doProcessing() {
|
||||||
System.out.println("JmsService is now processing");
|
System.out.println("JmsService is now processing");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,6 +6,6 @@ package com.iluwatar.business.delegate;
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public enum ServiceType {
|
public enum ServiceType {
|
||||||
|
|
||||||
EJB, JMS;
|
EJB, JMS;
|
||||||
}
|
}
|
||||||
|
@ -1,19 +0,0 @@
|
|||||||
package com.iluwatar.business.delegate;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import com.iluwatar.business.delegate.App;
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* Application test
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class AppTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void test() {
|
|
||||||
String[] args = {};
|
|
||||||
App.main(args);
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,78 @@
|
|||||||
|
package com.iluwatar.business.delegate;
|
||||||
|
|
||||||
|
import static org.mockito.Mockito.spy;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Business Delegate pattern adds an abstraction layer between the presentation and business
|
||||||
|
* tiers. By using the pattern we gain loose coupling between the tiers. The Business Delegate
|
||||||
|
* encapsulates knowledge about how to locate, connect to, and interact with the business objects
|
||||||
|
* that make up the application.
|
||||||
|
*
|
||||||
|
* <p>Some of the services the Business Delegate uses are instantiated directly, and some can be
|
||||||
|
* retrieved through service lookups. The Business Delegate itself may contain business logic too
|
||||||
|
* potentially tying together multiple service calls, exception handling, retrying etc.
|
||||||
|
*/
|
||||||
|
public class BusinessDelegateTest {
|
||||||
|
|
||||||
|
private EjbService ejbService;
|
||||||
|
|
||||||
|
private JmsService jmsService;
|
||||||
|
|
||||||
|
private BusinessLookup businessLookup;
|
||||||
|
|
||||||
|
private BusinessDelegate businessDelegate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method sets up the instance variables of this test class. It is executed before the
|
||||||
|
* execution of every test.
|
||||||
|
*/
|
||||||
|
@Before
|
||||||
|
public void setup() {
|
||||||
|
ejbService = spy(new EjbService());
|
||||||
|
jmsService = spy(new JmsService());
|
||||||
|
|
||||||
|
businessLookup = spy(new BusinessLookup());
|
||||||
|
businessLookup.setEjbService(ejbService);
|
||||||
|
businessLookup.setJmsService(jmsService);
|
||||||
|
|
||||||
|
businessDelegate = spy(new BusinessDelegate());
|
||||||
|
businessDelegate.setLookupService(businessLookup);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* In this example the client ({@link Client}) utilizes a business delegate (
|
||||||
|
* {@link BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate
|
||||||
|
* service and makes the service call.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void testBusinessDelegate() {
|
||||||
|
|
||||||
|
// setup a client object
|
||||||
|
Client client = new Client(businessDelegate);
|
||||||
|
|
||||||
|
// set the service type
|
||||||
|
businessDelegate.setServiceType(ServiceType.EJB);
|
||||||
|
|
||||||
|
// action
|
||||||
|
client.doTask();
|
||||||
|
|
||||||
|
// verifying that the businessDelegate was used by client during doTask() method.
|
||||||
|
verify(businessDelegate).doTask();
|
||||||
|
verify(ejbService).doProcessing();
|
||||||
|
|
||||||
|
// set the service type
|
||||||
|
businessDelegate.setServiceType(ServiceType.JMS);
|
||||||
|
|
||||||
|
// action
|
||||||
|
client.doTask();
|
||||||
|
|
||||||
|
// verifying that the businessDelegate was used by client during doTask() method.
|
||||||
|
verify(businessDelegate, times(2)).doTask();
|
||||||
|
verify(jmsService).doProcessing();
|
||||||
|
}
|
||||||
|
}
|
@ -6,6 +6,8 @@ permalink: /patterns/caching/
|
|||||||
categories: Other
|
categories: Other
|
||||||
tags:
|
tags:
|
||||||
- Java
|
- Java
|
||||||
|
- Difficulty-Intermediate
|
||||||
|
- Performance
|
||||||
---
|
---
|
||||||
|
|
||||||
**Intent:** To avoid expensive re-acquisition of resources by not releasing
|
**Intent:** To avoid expensive re-acquisition of resources by not releasing
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.iluwatar</groupId>
|
<groupId>com.iluwatar</groupId>
|
||||||
<artifactId>java-design-patterns</artifactId>
|
<artifactId>java-design-patterns</artifactId>
|
||||||
<version>1.7.0</version>
|
<version>1.9.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>caching</artifactId>
|
<artifactId>caching</artifactId>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -21,7 +21,7 @@ package com.iluwatar.caching;
|
|||||||
* application data. The cache itself is implemented as an internal (Java) data structure. It adopts
|
* 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
|
* 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
|
* 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
|
* {@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
|
* 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
|
* ({@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
|
* @param args command line args
|
||||||
*/
|
*/
|
||||||
public static void main(String[] 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
|
// and the App class to avoid Maven compilation errors. Set flag to
|
||||||
// true to run the tests with MongoDB (provided that MongoDB is
|
// true to run the tests with MongoDB (provided that MongoDB is
|
||||||
// installed and socket connection is open).
|
// installed and socket connection is open).
|
||||||
@ -65,8 +65,8 @@ public class App {
|
|||||||
|
|
||||||
AppManager.save(userAccount1);
|
AppManager.save(userAccount1);
|
||||||
System.out.println(AppManager.printCacheContent());
|
System.out.println(AppManager.printCacheContent());
|
||||||
userAccount1 = AppManager.find("001");
|
AppManager.find("001");
|
||||||
userAccount1 = AppManager.find("001");
|
AppManager.find("001");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -80,15 +80,15 @@ public class App {
|
|||||||
|
|
||||||
AppManager.save(userAccount2);
|
AppManager.save(userAccount2);
|
||||||
System.out.println(AppManager.printCacheContent());
|
System.out.println(AppManager.printCacheContent());
|
||||||
userAccount2 = AppManager.find("002");
|
AppManager.find("002");
|
||||||
System.out.println(AppManager.printCacheContent());
|
System.out.println(AppManager.printCacheContent());
|
||||||
userAccount2 = AppManager.find("002");
|
userAccount2 = AppManager.find("002");
|
||||||
userAccount2.setUserName("Jane G.");
|
userAccount2.setUserName("Jane G.");
|
||||||
AppManager.save(userAccount2);
|
AppManager.save(userAccount2);
|
||||||
System.out.println(AppManager.printCacheContent());
|
System.out.println(AppManager.printCacheContent());
|
||||||
userAccount2 = AppManager.find("002");
|
AppManager.find("002");
|
||||||
System.out.println(AppManager.printCacheContent());
|
System.out.println(AppManager.printCacheContent());
|
||||||
userAccount2 = AppManager.find("002");
|
AppManager.find("002");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -106,12 +106,12 @@ public class App {
|
|||||||
AppManager.save(userAccount4);
|
AppManager.save(userAccount4);
|
||||||
AppManager.save(userAccount5);
|
AppManager.save(userAccount5);
|
||||||
System.out.println(AppManager.printCacheContent());
|
System.out.println(AppManager.printCacheContent());
|
||||||
userAccount3 = AppManager.find("003");
|
AppManager.find("003");
|
||||||
System.out.println(AppManager.printCacheContent());
|
System.out.println(AppManager.printCacheContent());
|
||||||
UserAccount userAccount6 = new UserAccount("006", "Yasha", "She is an only child.");
|
UserAccount userAccount6 = new UserAccount("006", "Yasha", "She is an only child.");
|
||||||
AppManager.save(userAccount6);
|
AppManager.save(userAccount6);
|
||||||
System.out.println(AppManager.printCacheContent());
|
System.out.println(AppManager.printCacheContent());
|
||||||
userAccount4 = AppManager.find("004");
|
AppManager.find("004");
|
||||||
System.out.println(AppManager.printCacheContent());
|
System.out.println(AppManager.printCacheContent());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -15,24 +15,30 @@ public class AppManager {
|
|||||||
|
|
||||||
private static CachingPolicy cachingPolicy;
|
private static CachingPolicy cachingPolicy;
|
||||||
|
|
||||||
|
private AppManager() {
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* Developer/Tester is able to choose whether the application should use MongoDB as its underlying
|
* 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
|
* data storage or a simple Java data structure to (temporarily) store the data/objects during
|
||||||
* runtime.
|
* runtime.
|
||||||
*/
|
*/
|
||||||
public static void initDB(boolean useMongoDB) {
|
public static void initDb(boolean useMongoDb) {
|
||||||
if (useMongoDB) {
|
if (useMongoDb) {
|
||||||
try {
|
try {
|
||||||
DBManager.connect();
|
DbManager.connect();
|
||||||
} catch (ParseException e) {
|
} catch (ParseException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
DBManager.createVirtualDB();
|
DbManager.createVirtualDb();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize caching policy
|
||||||
|
*/
|
||||||
public static void initCachingPolicy(CachingPolicy policy) {
|
public static void initCachingPolicy(CachingPolicy policy) {
|
||||||
cachingPolicy = policy;
|
cachingPolicy = policy;
|
||||||
if (cachingPolicy == CachingPolicy.BEHIND) {
|
if (cachingPolicy == CachingPolicy.BEHIND) {
|
||||||
@ -50,15 +56,21 @@ public class AppManager {
|
|||||||
CacheStore.initCapacity(capacity);
|
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) {
|
if (cachingPolicy == CachingPolicy.THROUGH || cachingPolicy == CachingPolicy.AROUND) {
|
||||||
return CacheStore.readThrough(userID);
|
return CacheStore.readThrough(userId);
|
||||||
} else if (cachingPolicy == CachingPolicy.BEHIND) {
|
} else if (cachingPolicy == CachingPolicy.BEHIND) {
|
||||||
return CacheStore.readThroughWithWriteBackPolicy(userID);
|
return CacheStore.readThroughWithWriteBackPolicy(userId);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save user account
|
||||||
|
*/
|
||||||
public static void save(UserAccount userAccount) {
|
public static void save(UserAccount userAccount) {
|
||||||
if (cachingPolicy == CachingPolicy.THROUGH) {
|
if (cachingPolicy == CachingPolicy.THROUGH) {
|
||||||
CacheStore.writeThrough(userAccount);
|
CacheStore.writeThrough(userAccount);
|
||||||
|
@ -9,73 +9,99 @@ import java.util.ArrayList;
|
|||||||
*/
|
*/
|
||||||
public class CacheStore {
|
public class CacheStore {
|
||||||
|
|
||||||
static LRUCache cache = null;
|
static LruCache cache = null;
|
||||||
|
|
||||||
public static void initCapacity(int capacity) {
|
private CacheStore() {
|
||||||
if (null == cache)
|
|
||||||
cache = new LRUCache(capacity);
|
|
||||||
else
|
|
||||||
cache.setCapacity(capacity);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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!");
|
System.out.println("# Cache Hit!");
|
||||||
return cache.get(userID);
|
return cache.get(userId);
|
||||||
}
|
}
|
||||||
System.out.println("# Cache Miss!");
|
System.out.println("# Cache Miss!");
|
||||||
UserAccount userAccount = DBManager.readFromDB(userID);
|
UserAccount userAccount = DbManager.readFromDb(userId);
|
||||||
cache.set(userID, userAccount);
|
cache.set(userId, userAccount);
|
||||||
return userAccount;
|
return userAccount;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get user account using write-through cache
|
||||||
|
*/
|
||||||
public static void writeThrough(UserAccount userAccount) {
|
public static void writeThrough(UserAccount userAccount) {
|
||||||
if (cache.contains(userAccount.getUserID())) {
|
if (cache.contains(userAccount.getUserId())) {
|
||||||
DBManager.updateDB(userAccount);
|
DbManager.updateDb(userAccount);
|
||||||
} else {
|
} 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) {
|
public static void writeAround(UserAccount userAccount) {
|
||||||
if (cache.contains(userAccount.getUserID())) {
|
if (cache.contains(userAccount.getUserId())) {
|
||||||
DBManager.updateDB(userAccount);
|
DbManager.updateDb(userAccount);
|
||||||
cache.invalidate(userAccount.getUserID()); // Cache data has been updated -- remove older
|
cache.invalidate(userAccount.getUserId()); // Cache data has been updated -- remove older
|
||||||
// version from cache.
|
// version from cache.
|
||||||
} else {
|
} 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!");
|
System.out.println("# Cache Hit!");
|
||||||
return cache.get(userID);
|
return cache.get(userId);
|
||||||
}
|
}
|
||||||
System.out.println("# Cache Miss!");
|
System.out.println("# Cache Miss!");
|
||||||
UserAccount userAccount = DBManager.readFromDB(userID);
|
UserAccount userAccount = DbManager.readFromDb(userId);
|
||||||
if (cache.isFull()) {
|
if (cache.isFull()) {
|
||||||
System.out.println("# Cache is FULL! Writing LRU data to DB...");
|
System.out.println("# Cache is FULL! Writing LRU data to DB...");
|
||||||
UserAccount toBeWrittenToDB = cache.getLRUData();
|
UserAccount toBeWrittenToDb = cache.getLruData();
|
||||||
DBManager.upsertDB(toBeWrittenToDB);
|
DbManager.upsertDb(toBeWrittenToDb);
|
||||||
}
|
}
|
||||||
cache.set(userID, userAccount);
|
cache.set(userId, userAccount);
|
||||||
return userAccount;
|
return userAccount;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set user account
|
||||||
|
*/
|
||||||
public static void writeBehind(UserAccount userAccount) {
|
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...");
|
System.out.println("# Cache is FULL! Writing LRU data to DB...");
|
||||||
UserAccount toBeWrittenToDB = cache.getLRUData();
|
UserAccount toBeWrittenToDb = cache.getLruData();
|
||||||
DBManager.upsertDB(toBeWrittenToDB);
|
DbManager.upsertDb(toBeWrittenToDb);
|
||||||
}
|
}
|
||||||
cache.set(userAccount.getUserID(), userAccount);
|
cache.set(userAccount.getUserId(), userAccount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clears cache
|
||||||
|
*/
|
||||||
public static void clearCache() {
|
public static void clearCache() {
|
||||||
if (null != cache)
|
if (null != cache) {
|
||||||
cache.clear();
|
cache.clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -83,14 +109,18 @@ public class CacheStore {
|
|||||||
*/
|
*/
|
||||||
public static void flushCache() {
|
public static void flushCache() {
|
||||||
System.out.println("# flushCache...");
|
System.out.println("# flushCache...");
|
||||||
if (null == cache)
|
if (null == cache) {
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
ArrayList<UserAccount> listOfUserAccounts = cache.getCacheDataInListForm();
|
ArrayList<UserAccount> listOfUserAccounts = cache.getCacheDataInListForm();
|
||||||
for (UserAccount userAccount : listOfUserAccounts) {
|
for (UserAccount userAccount : listOfUserAccounts) {
|
||||||
DBManager.upsertDB(userAccount);
|
DbManager.upsertDb(userAccount);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Print user accounts
|
||||||
|
*/
|
||||||
public static String print() {
|
public static String print() {
|
||||||
ArrayList<UserAccount> listOfUserAccounts = cache.getCacheDataInListForm();
|
ArrayList<UserAccount> listOfUserAccounts = cache.getCacheDataInListForm();
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
|
@ -21,7 +21,7 @@ import com.mongodb.client.model.UpdateOptions;
|
|||||||
* during runtime (createVirtualDB()).</p>
|
* during runtime (createVirtualDB()).</p>
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class DBManager {
|
public class DbManager {
|
||||||
|
|
||||||
private static MongoClient mongoClient;
|
private static MongoClient mongoClient;
|
||||||
private static MongoDatabase db;
|
private static MongoDatabase db;
|
||||||
@ -29,21 +29,34 @@ public class DBManager {
|
|||||||
|
|
||||||
private static HashMap<String, UserAccount> virtualDB;
|
private static HashMap<String, UserAccount> virtualDB;
|
||||||
|
|
||||||
public static void createVirtualDB() {
|
private DbManager() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create DB
|
||||||
|
*/
|
||||||
|
public static void createVirtualDb() {
|
||||||
useMongoDB = false;
|
useMongoDB = false;
|
||||||
virtualDB = new HashMap<String, UserAccount>();
|
virtualDB = new HashMap<String, UserAccount>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Connect to DB
|
||||||
|
*/
|
||||||
public static void connect() throws ParseException {
|
public static void connect() throws ParseException {
|
||||||
useMongoDB = true;
|
useMongoDB = true;
|
||||||
mongoClient = new MongoClient();
|
mongoClient = new MongoClient();
|
||||||
db = mongoClient.getDatabase("test");
|
db = mongoClient.getDatabase("test");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static UserAccount readFromDB(String userID) {
|
/**
|
||||||
|
* Read user account from DB
|
||||||
|
*/
|
||||||
|
public static UserAccount readFromDb(String userId) {
|
||||||
if (!useMongoDB) {
|
if (!useMongoDB) {
|
||||||
if (virtualDB.containsKey(userID))
|
if (virtualDB.containsKey(userId)) {
|
||||||
return virtualDB.get(userID);
|
return virtualDB.get(userId);
|
||||||
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (null == db) {
|
if (null == db) {
|
||||||
@ -54,18 +67,22 @@ public class DBManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
FindIterable<Document> iterable =
|
FindIterable<Document> iterable =
|
||||||
db.getCollection("user_accounts").find(new Document("userID", userID));
|
db.getCollection("user_accounts").find(new Document("userID", userId));
|
||||||
if (iterable == null)
|
if (iterable == null) {
|
||||||
return null;
|
return null;
|
||||||
|
}
|
||||||
Document doc = iterable.first();
|
Document doc = iterable.first();
|
||||||
UserAccount userAccount =
|
UserAccount userAccount =
|
||||||
new UserAccount(userID, doc.getString("userName"), doc.getString("additionalInfo"));
|
new UserAccount(userId, doc.getString("userName"), doc.getString("additionalInfo"));
|
||||||
return userAccount;
|
return userAccount;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void writeToDB(UserAccount userAccount) {
|
/**
|
||||||
|
* Write user account to DB
|
||||||
|
*/
|
||||||
|
public static void writeToDb(UserAccount userAccount) {
|
||||||
if (!useMongoDB) {
|
if (!useMongoDB) {
|
||||||
virtualDB.put(userAccount.getUserID(), userAccount);
|
virtualDB.put(userAccount.getUserId(), userAccount);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (null == db) {
|
if (null == db) {
|
||||||
@ -76,13 +93,16 @@ public class DBManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
db.getCollection("user_accounts").insertOne(
|
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()));
|
userAccount.getUserName()).append("additionalInfo", userAccount.getAdditionalInfo()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void updateDB(UserAccount userAccount) {
|
/**
|
||||||
|
* Update DB
|
||||||
|
*/
|
||||||
|
public static void updateDb(UserAccount userAccount) {
|
||||||
if (!useMongoDB) {
|
if (!useMongoDB) {
|
||||||
virtualDB.put(userAccount.getUserID(), userAccount);
|
virtualDB.put(userAccount.getUserId(), userAccount);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (null == db) {
|
if (null == db) {
|
||||||
@ -93,7 +113,7 @@ public class DBManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
db.getCollection("user_accounts").updateOne(
|
db.getCollection("user_accounts").updateOne(
|
||||||
new Document("userID", userAccount.getUserID()),
|
new Document("userID", userAccount.getUserId()),
|
||||||
new Document("$set", new Document("userName", userAccount.getUserName()).append(
|
new Document("$set", new Document("userName", userAccount.getUserName()).append(
|
||||||
"additionalInfo", userAccount.getAdditionalInfo())));
|
"additionalInfo", userAccount.getAdditionalInfo())));
|
||||||
}
|
}
|
||||||
@ -102,9 +122,9 @@ public class DBManager {
|
|||||||
*
|
*
|
||||||
* Insert data into DB if it does not exist. Else, update it.
|
* 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) {
|
if (!useMongoDB) {
|
||||||
virtualDB.put(userAccount.getUserID(), userAccount);
|
virtualDB.put(userAccount.getUserId(), userAccount);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (null == db) {
|
if (null == db) {
|
||||||
@ -115,8 +135,8 @@ public class DBManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
db.getCollection("user_accounts").updateOne(
|
db.getCollection("user_accounts").updateOne(
|
||||||
new Document("userID", userAccount.getUserID()),
|
new Document("userID", userAccount.getUserId()),
|
||||||
new Document("$set", new Document("userID", userAccount.getUserID()).append("userName",
|
new Document("$set", new Document("userID", userAccount.getUserId()).append("userName",
|
||||||
userAccount.getUserName()).append("additionalInfo", userAccount.getAdditionalInfo())),
|
userAccount.getUserName()).append("additionalInfo", userAccount.getAdditionalInfo())),
|
||||||
new UpdateOptions().upsert(true));
|
new UpdateOptions().upsert(true));
|
||||||
}
|
}
|
@ -12,16 +12,16 @@ import java.util.HashMap;
|
|||||||
* LRU data is always at the end of the list.
|
* LRU data is always at the end of the list.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class LRUCache {
|
public class LruCache {
|
||||||
|
|
||||||
class Node {
|
class Node {
|
||||||
String userID;
|
String userId;
|
||||||
UserAccount userAccount;
|
UserAccount userAccount;
|
||||||
Node previous;
|
Node previous;
|
||||||
Node next;
|
Node next;
|
||||||
|
|
||||||
public Node(String userID, UserAccount userAccount) {
|
public Node(String userId, UserAccount userAccount) {
|
||||||
this.userID = userID;
|
this.userId = userId;
|
||||||
this.userAccount = userAccount;
|
this.userAccount = userAccount;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -31,13 +31,16 @@ public class LRUCache {
|
|||||||
Node head = null;
|
Node head = null;
|
||||||
Node end = null;
|
Node end = null;
|
||||||
|
|
||||||
public LRUCache(int capacity) {
|
public LruCache(int capacity) {
|
||||||
this.capacity = capacity;
|
this.capacity = capacity;
|
||||||
}
|
}
|
||||||
|
|
||||||
public UserAccount get(String userID) {
|
/**
|
||||||
if (cache.containsKey(userID)) {
|
* Get user account
|
||||||
Node node = cache.get(userID);
|
*/
|
||||||
|
public UserAccount get(String userId) {
|
||||||
|
if (cache.containsKey(userId)) {
|
||||||
|
Node node = cache.get(userId);
|
||||||
remove(node);
|
remove(node);
|
||||||
setHead(node);
|
setHead(node);
|
||||||
return node.userAccount;
|
return node.userAccount;
|
||||||
@ -69,52 +72,63 @@ public class LRUCache {
|
|||||||
public void setHead(Node node) {
|
public void setHead(Node node) {
|
||||||
node.next = head;
|
node.next = head;
|
||||||
node.previous = null;
|
node.previous = null;
|
||||||
if (head != null)
|
if (head != null) {
|
||||||
head.previous = node;
|
head.previous = node;
|
||||||
|
}
|
||||||
head = node;
|
head = node;
|
||||||
if (end == null)
|
if (end == null) {
|
||||||
end = head;
|
end = head;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void set(String userID, UserAccount userAccount) {
|
/**
|
||||||
if (cache.containsKey(userID)) {
|
* Set user account
|
||||||
Node old = cache.get(userID);
|
*/
|
||||||
|
public void set(String userId, UserAccount userAccount) {
|
||||||
|
if (cache.containsKey(userId)) {
|
||||||
|
Node old = cache.get(userId);
|
||||||
old.userAccount = userAccount;
|
old.userAccount = userAccount;
|
||||||
remove(old);
|
remove(old);
|
||||||
setHead(old);
|
setHead(old);
|
||||||
} else {
|
} else {
|
||||||
Node newNode = new Node(userID, userAccount);
|
Node newNode = new Node(userId, userAccount);
|
||||||
if (cache.size() >= capacity) {
|
if (cache.size() >= capacity) {
|
||||||
System.out.println("# Cache is FULL! Removing " + end.userID + " from cache...");
|
System.out.println("# Cache is FULL! Removing " + end.userId + " from cache...");
|
||||||
cache.remove(end.userID); // remove LRU data from cache.
|
cache.remove(end.userId); // remove LRU data from cache.
|
||||||
remove(end);
|
remove(end);
|
||||||
setHead(newNode);
|
setHead(newNode);
|
||||||
} else {
|
} else {
|
||||||
setHead(newNode);
|
setHead(newNode);
|
||||||
}
|
}
|
||||||
cache.put(userID, newNode);
|
cache.put(userId, newNode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean contains(String userID) {
|
public boolean contains(String userId) {
|
||||||
return cache.containsKey(userID);
|
return cache.containsKey(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void invalidate(String userID) {
|
/**
|
||||||
System.out.println("# " + userID + " has been updated! Removing older version from cache...");
|
* Invalidate cache for user
|
||||||
Node toBeRemoved = cache.get(userID);
|
*/
|
||||||
|
public void invalidate(String userId) {
|
||||||
|
System.out.println("# " + userId + " has been updated! Removing older version from cache...");
|
||||||
|
Node toBeRemoved = cache.get(userId);
|
||||||
remove(toBeRemoved);
|
remove(toBeRemoved);
|
||||||
cache.remove(userID);
|
cache.remove(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isFull() {
|
public boolean isFull() {
|
||||||
return cache.size() >= capacity;
|
return cache.size() >= capacity;
|
||||||
}
|
}
|
||||||
|
|
||||||
public UserAccount getLRUData() {
|
public UserAccount getLruData() {
|
||||||
return end.userAccount;
|
return end.userAccount;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear cache
|
||||||
|
*/
|
||||||
public void clear() {
|
public void clear() {
|
||||||
head = null;
|
head = null;
|
||||||
end = null;
|
end = null;
|
||||||
@ -135,6 +149,9 @@ public class LRUCache {
|
|||||||
return listOfCacheData;
|
return listOfCacheData;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set cache capacity
|
||||||
|
*/
|
||||||
public void setCapacity(int newCapacity) {
|
public void setCapacity(int newCapacity) {
|
||||||
if (capacity > newCapacity) {
|
if (capacity > newCapacity) {
|
||||||
clear(); // Behavior can be modified to accommodate for decrease in cache size. For now, we'll
|
clear(); // Behavior can be modified to accommodate for decrease in cache size. For now, we'll
|
@ -6,22 +6,25 @@ package com.iluwatar.caching;
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class UserAccount {
|
public class UserAccount {
|
||||||
private String userID;
|
private String userId;
|
||||||
private String userName;
|
private String userName;
|
||||||
private String additionalInfo;
|
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.userName = userName;
|
||||||
this.additionalInfo = additionalInfo;
|
this.additionalInfo = additionalInfo;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getUserID() {
|
public String getUserId() {
|
||||||
return userID;
|
return userId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setUserID(String userID) {
|
public void setUserId(String userId) {
|
||||||
this.userID = userID;
|
this.userId = userId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getUserName() {
|
public String getUserName() {
|
||||||
@ -42,6 +45,6 @@ public class UserAccount {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return userID + ", " + userName + ", " + additionalInfo;
|
return userId + ", " + userName + ", " + additionalInfo;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -16,7 +16,7 @@ public class AppTest {
|
|||||||
*/
|
*/
|
||||||
@Before
|
@Before
|
||||||
public void setUp() {
|
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
|
// to avoid Maven compilation errors. Set flag to true to run the
|
||||||
// tests with MongoDB (provided that MongoDB is installed and socket
|
// tests with MongoDB (provided that MongoDB is installed and socket
|
||||||
// connection is open).
|
// connection is open).
|
||||||
|
@ -4,7 +4,11 @@ title: Callback
|
|||||||
folder: callback
|
folder: callback
|
||||||
permalink: /patterns/callback/
|
permalink: /patterns/callback/
|
||||||
categories: Other
|
categories: Other
|
||||||
tags: Java
|
tags:
|
||||||
|
- Java
|
||||||
|
- Difficulty-Beginner
|
||||||
|
- Functional
|
||||||
|
- Idiom
|
||||||
---
|
---
|
||||||
|
|
||||||
**Intent:** Callback is a piece of executable code that is passed as an
|
**Intent:** Callback is a piece of executable code that is passed as an
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.iluwatar</groupId>
|
<groupId>com.iluwatar</groupId>
|
||||||
<artifactId>java-design-patterns</artifactId>
|
<artifactId>java-design-patterns</artifactId>
|
||||||
<version>1.7.0</version>
|
<version>1.9.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>callback</artifactId>
|
<artifactId>callback</artifactId>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -2,20 +2,24 @@ package com.iluwatar.callback;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* Callback pattern is more native for functional languages where functions are treated as first-class citizens.
|
* Callback pattern is more native for functional languages where functions are treated as
|
||||||
* Prior to Java 8 callbacks can be simulated using simple (alike command) interfaces.
|
* first-class citizens. Prior to Java 8 callbacks can be simulated using simple (alike command)
|
||||||
|
* interfaces.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class App {
|
public class App {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
/**
|
||||||
Task task = new SimpleTask();
|
* Program entry point
|
||||||
Callback callback = new Callback() {
|
*/
|
||||||
@Override
|
public static void main(String[] args) {
|
||||||
public void call() {
|
Task task = new SimpleTask();
|
||||||
System.out.println("I'm done now.");
|
Callback callback = new Callback() {
|
||||||
}
|
@Override
|
||||||
};
|
public void call() {
|
||||||
task.executeWith(callback);
|
System.out.println("I'm done now.");
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
task.executeWith(callback);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,5 +7,5 @@ package com.iluwatar.callback;
|
|||||||
*/
|
*/
|
||||||
public interface Callback {
|
public interface Callback {
|
||||||
|
|
||||||
public void call();
|
void call();
|
||||||
}
|
}
|
||||||
|
@ -7,9 +7,8 @@ package com.iluwatar.callback;
|
|||||||
*/
|
*/
|
||||||
public class SimpleTask extends Task {
|
public class SimpleTask extends Task {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void execute() {
|
public void execute() {
|
||||||
System.out.println("Perform some important activity and after call the callback method.");
|
System.out.println("Perform some important activity and after call the callback method.");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user