Compare commits

..

11 Commits
1.8.0 ... urm

619 changed files with 9720 additions and 12917 deletions

View File

@ -1,18 +1,20 @@
language: java language: java
jdk: jdk:
- oraclejdk8 - oraclejdk8
env: env:
global: global:
- GH_REF: github.com/iluwatar/java-design-patterns.git - GH_REF: github.com/iluwatar/java-design-patterns.git
- secure: LxTDuNS/rBWIvKkaEqr79ImZAe48mCdoYCF41coxNXgNoippo4GIBArknqtv+XvdkiuRZ1yGyj6pn8GU33c/yn+krddTUkVCwTbVatbalW5jhQjDbHYym/JcxaK9ZS/3JTeGcWrBgiPqHEEDhCf26vPZsXoMSeVCEORVKTp1BSg= - secure: "LxTDuNS/rBWIvKkaEqr79ImZAe48mCdoYCF41coxNXgNoippo4GIBArknqtv+XvdkiuRZ1yGyj6pn8GU33c/yn+krddTUkVCwTbVatbalW5jhQjDbHYym/JcxaK9ZS/3JTeGcWrBgiPqHEEDhCf26vPZsXoMSeVCEORVKTp1BSg="
before_install: before_install:
- export DISPLAY=:99.0 - "export DISPLAY=:99.0"
- sh -e /etc/init.d/xvfb start - "sh -e /etc/init.d/xvfb start"
after_success: after_success:
- mvn clean test jacoco:report coveralls:report - mvn clean test jacoco:report coveralls:report
- bash update-ghpages.sh - bash update-ghpages.sh
# Migration to container-based infrastructure
sudo: false sudo: false

View File

@ -1,13 +0,0 @@
# 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

View File

@ -23,16 +23,10 @@ are familiar with the patterns.
# Getting started # Getting started
Before you dive into the material, you should be familiar with various Before you dive into the material, you should be familiar with various
[Programming/Software Design Principles](http://webpro.github.io/programming-principles/). [Programming/Software Design Principles](http://webpro.github.io/programming-principles/).
All designs should be as simple as possible. You should start with KISS, YAGNI, Once you are familiar with these concepts you can start drilling down into patterns by any of the following approaches
and Do The Simplest Thing That Could Possibly Work principles. Complexity and
patterns should only be introduced when they are needed for practical
extensibility.
Once you are familiar with these concepts you can start drilling down into
patterns by any of the following approaches
- Using difficulty tags, `Difficulty-Beginner`, `Difficulty-Intermediate` & `Difficulty-Expert`. - Using difficulty tags, `Difficulty-Beginner`, `Difficulty-Intermediate` & `Difficulty-Expert`.
- Using pattern categories, `Creational`, `Behavioral` and others. - Using pattern categories, `Creational`, `Behavioral` and others.
@ -44,6 +38,7 @@ If you are willing to contribute to the project you will find the relevant infor
# Credits # Credits
* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612)
* [Effective Java (2nd Edition)](http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683) * [Effective Java (2nd Edition)](http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683)
* [Java Generics and Collections](http://www.amazon.com/Java-Generics-Collections-Maurice-Naftalin/dp/0596527756/) * [Java Generics and Collections](http://www.amazon.com/Java-Generics-Collections-Maurice-Naftalin/dp/0596527756/)
* [Let's Modify the Objects-First Approach into Design-Patterns-First](http://edu.pecinovsky.cz/papers/2006_ITiCSE_Design_Patterns_First.pdf) * [Let's Modify the Objects-First Approach into Design-Patterns-First](http://edu.pecinovsky.cz/papers/2006_ITiCSE_Design_Patterns_First.pdf)
@ -53,6 +48,7 @@ If you are willing to contribute to the project you will find the relevant infor
* [Patterns of Enterprise Application Architecture](http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420) * [Patterns of Enterprise Application Architecture](http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420)
* [Spring Data](http://www.amazon.com/Spring-Data-Mark-Pollack/dp/1449323952/ref=sr_1_1) * [Spring Data](http://www.amazon.com/Spring-Data-Mark-Pollack/dp/1449323952/ref=sr_1_1)
* [J2EE Design Patterns](http://www.amazon.com/J2EE-Design-Patterns-William-Crawford/dp/0596004273/ref=sr_1_2) * [J2EE Design Patterns](http://www.amazon.com/J2EE-Design-Patterns-William-Crawford/dp/0596004273/ref=sr_1_2)
* [Pattern Oriented Software Architecture Vol I-V](http://www.amazon.com/Pattern-Oriented-Software-Architecture-Volume-Patterns/dp/0471958697)
# License # License

View File

@ -4,13 +4,9 @@ title: Abstract Factory
folder: abstract-factory folder: abstract-factory
permalink: /patterns/abstract-factory/ permalink: /patterns/abstract-factory/
categories: Creational categories: Creational
tags: tags: Java
- Java
- Gang Of Four
--- ---
**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.
@ -26,7 +22,3 @@ objects without specifying their concrete classes.
**Real world examples:** **Real world examples:**
* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) * [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html)
**Credits**
* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612)

View File

@ -1,18 +1,19 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" <project
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
<modelVersion>4.0.0</modelVersion> xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<parent> <modelVersion>4.0.0</modelVersion>
<groupId>com.iluwatar</groupId> <parent>
<artifactId>java-design-patterns</artifactId> <groupId>com.iluwatar</groupId>
<version>1.8.0</version> <artifactId>java-design-patterns</artifactId>
</parent> <version>1.6.0</version>
<artifactId>abstract-factory</artifactId> </parent>
<dependencies> <artifactId>abstract-factory</artifactId>
<dependency> <dependencies>
<groupId>junit</groupId> <dependency>
<artifactId>junit</artifactId> <groupId>junit</groupId>
<scope>test</scope> <artifactId>junit</artifactId>
</dependency> <scope>test</scope>
</dependencies> </dependency>
</dependencies>
</project> </project>

View File

@ -3,108 +3,71 @@ package com.iluwatar.abstractfactory;
/** /**
* *
* The Abstract Factory pattern provides a way to encapsulate a group of individual factories that * The essence of the Abstract Factory pattern is a factory interface
* have a common theme without specifying their concrete classes. In normal usage, the client * ({@link KingdomFactory}) and its implementations ({@link ElfKingdomFactory},
* software creates a concrete implementation of the abstract factory and then uses the generic * {@link OrcKingdomFactory}).
* interface of the factory to create the concrete objects that are part of the theme. The client
* does not know (or care) which concrete objects it gets from each of these internal factories,
* since it uses only the generic interfaces of their products. This pattern separates the details
* of implementation of a set of objects from their general usage and relies on object composition,
* as object creation is implemented in methods exposed in the factory interface.
* <p> * <p>
* The essence of the Abstract Factory pattern is a factory interface ({@link KingdomFactory}) and * The example uses both concrete implementations to create a king, a castle and
* its implementations ({@link ElfKingdomFactory}, {@link OrcKingdomFactory}). The example uses both * an army.
* concrete implementations to 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
* Creates kingdom * @param factory
* */
* @param factory public void createKingdom(final KingdomFactory factory) {
*/ setKing(factory.createKing());
public void createKingdom(final KingdomFactory factory) { setCastle(factory.createCastle());
setKing(factory.createKing()); setArmy(factory.createArmy());
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;
}
/**
* 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"); ElfKingdomFactory getElfKingdomFactory() {
KingdomFactory orcKingdomFactory; return new ElfKingdomFactory();
orcKingdomFactory = app.getOrcKingdomFactory(); }
app.createKingdom(orcKingdomFactory);
System.out.println(app.getArmy().getDescription()); OrcKingdomFactory getOrcKingdomFactory() {
System.out.println(app.getCastle().getDescription()); return new OrcKingdomFactory();
System.out.println(app.getKing().getDescription()); }
} 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;
}
} }

View File

@ -7,5 +7,5 @@ package com.iluwatar.abstractfactory;
*/ */
public interface Army { public interface Army {
String getDescription(); String getDescription();
} }

View File

@ -7,5 +7,5 @@ package com.iluwatar.abstractfactory;
*/ */
public interface Castle { public interface Castle {
String getDescription(); String getDescription();
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -7,5 +7,5 @@ package com.iluwatar.abstractfactory;
*/ */
public interface King { public interface King {
String getDescription(); String getDescription();
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -7,15 +7,16 @@ 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();
}
} }

View File

@ -1,5 +1,4 @@
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;
@ -8,71 +7,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());
} }
} }

View File

@ -4,13 +4,9 @@ title: Adapter
folder: adapter folder: adapter
permalink: /patterns/adapter/ permalink: /patterns/adapter/
categories: Structural categories: Structural
tags: tags: Java
- Java
- Gang Of Four
--- ---
**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.
@ -26,7 +22,3 @@ incompatible interfaces.
**Real world examples:** **Real world examples:**
* [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) * [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29)
**Credits**
* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612)

View File

@ -1,23 +1,19 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" <project
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
<modelVersion>4.0.0</modelVersion> xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<parent> <modelVersion>4.0.0</modelVersion>
<groupId>com.iluwatar</groupId> <parent>
<artifactId>java-design-patterns</artifactId> <groupId>com.iluwatar</groupId>
<version>1.8.0</version> <artifactId>java-design-patterns</artifactId>
</parent> <version>1.6.0</version>
<artifactId>adapter</artifactId> </parent>
<dependencies> <artifactId>adapter</artifactId>
<dependency> <dependencies>
<groupId>junit</groupId> <dependency>
<artifactId>junit</artifactId> <groupId>junit</groupId>
<scope>test</scope> <artifactId>junit</artifactId>
</dependency> <scope>test</scope>
<dependency> </dependency>
<groupId>org.mockito</groupId> </dependencies>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project> </project>

View File

@ -1,28 +1,25 @@
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.
* *
* <p>There are two variations of the Adapter pattern: The class adapter implements the adaptee's * There are two variations of the Adapter pattern: The class adapter implements
* interface whereas the object adapter uses composition to contain the adaptee in the adapter * the adaptee's interface whereas the object adapter uses composition to
* object. This example uses the object adapter approach. * contain the adaptee in the adapter object. This example uses the object
* adapter approach.
* <p>
* The Adapter ({@link GnomeEngineer}) converts the interface of the target class
* ({@link GoblinGlider}) into a suitable one expected by the client
* ({@link GnomeEngineeringManager}).
* *
* <p>The Adapter ({@link GnomeEngineer}) converts the interface of the target class (
* {@link GoblinGlider}) into a suitable one expected by the client ({@link GnomeEngineeringManager}
* ).
*/ */
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) { Engineer manager = new GnomeEngineeringManager();
Engineer manager = new GnomeEngineeringManager(new GnomeEngineer()); manager.operateDevice();
manager.operateDevice(); }
}
} }

View File

@ -7,5 +7,6 @@ package com.iluwatar.adapter;
*/ */
public interface Engineer { public interface Engineer {
void operateDevice(); void operateDevice();
} }

View File

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

View File

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

View File

@ -7,15 +7,15 @@ package com.iluwatar.adapter;
*/ */
public class GoblinGlider { public class GoblinGlider {
public void attachGlider() { public void attachGlider() {
System.out.println("Glider attached."); System.out.println("Glider attached.");
} }
public void gainSpeed() { public void gainSpeed() {
System.out.println("Gaining speed."); System.out.println("Gaining speed.");
} }
public void takeOff() { public void takeOff() {
System.out.println("Lift-off!"); System.out.println("Lift-off!");
} }
} }

View File

@ -1,68 +0,0 @@
package com.iluwatar.adapter;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
/**
* 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>There are two variations of the Adapter pattern:
* The class adapter implements the adaptee's
* interface whereas the object adapter uses composition to contain the adaptee in the adapter
* object. This example uses the object adapter approach.
*
* <p>The Adapter ({@link GnomeEngineer}) converts the interface
* of the target class ({@link GoblinGlider}) into a suitable one expected by
* the client ({@link GnomeEngineeringManager}
* ).
*/
public class AdapterPatternTest {
private Map<String, Object> beans;
private static final String ENGINEER_BEAN = "engineer";
private static final String MANAGER_BEAN = "manager";
/**
* This method runs before the test execution and sets the bean objects in the beans Map.
*/
@Before
public void setup() {
beans = new HashMap<>();
GnomeEngineer gnomeEngineer = spy(new GnomeEngineer());
beans.put(ENGINEER_BEAN, gnomeEngineer);
GnomeEngineeringManager manager = new GnomeEngineeringManager();
manager.setEngineer((GnomeEngineer) beans.get(ENGINEER_BEAN));
beans.put(MANAGER_BEAN, manager);
}
/**
* This test asserts that when we call operateDevice() method on a manager bean, it is internally
* calling operateDevice method on the engineer object. The Adapter ({@link GnomeEngineer})
* converts the interface of the target class ( {@link GoblinGlider}) into a suitable one expected
* by the client ({@link GnomeEngineeringManager} ).
*/
@Test
public void testAdapter() {
Engineer manager = (Engineer) beans.get(MANAGER_BEAN);
// when manager is asked to operate device
manager.operateDevice();
// Manager internally calls the engineer object to operateDevice
Engineer engineer = (Engineer) beans.get(ENGINEER_BEAN);
verify(engineer).operateDevice();
}
}

View File

@ -0,0 +1,19 @@
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);
}
}

View File

@ -1,18 +1,19 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" <project
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
<modelVersion>4.0.0</modelVersion> xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<parent> <modelVersion>4.0.0</modelVersion>
<groupId>com.iluwatar</groupId> <parent>
<artifactId>java-design-patterns</artifactId> <groupId>com.iluwatar</groupId>
<version>1.8.0</version> <artifactId>java-design-patterns</artifactId>
</parent> <version>1.6.0</version>
<artifactId>async-method-invocation</artifactId> </parent>
<dependencies> <artifactId>async-method-invocation</artifactId>
<dependency> <dependencies>
<groupId>junit</groupId> <dependency>
<artifactId>junit</artifactId> <groupId>junit</groupId>
<scope>test</scope> <artifactId>junit</artifactId>
</dependency> <scope>test</scope>
</dependencies> </dependency>
</dependencies>
</project> </project>

View File

@ -4,24 +4,23 @@ import java.util.concurrent.Callable;
/** /**
* This application demonstrates the async method invocation pattern. Key parts of the pattern are * 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 * <code>AsyncResult</code> which is an intermediate container for an asynchronously evaluated value,
* 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> that manages the execution of the async tasks. * <code>AsyncExecutor</code> 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 * The main method shows example flow of async invocations. The main thread starts multiple tasks with
* with variable durations and then continues its own work. When the main thread has done it's job * variable durations and then continues its own work. When the main thread has done it's job it collects
* it collects the results of the async tasks. Two of the tasks are handled with callbacks, meaning * the results of the async tasks. Two of the tasks are handled with callbacks, meaning the callbacks are
* the callbacks are executed immediately when the tasks complete. * executed immediately when the tasks complete.
* <p> * <p>
* Noteworthy difference of thread usage between the async results and callbacks is that the async * Noteworthy difference of thread usage between the async results and callbacks is that the async results
* results are collected in the main thread but the callbacks are executed within the worker * are collected in the main thread but the callbacks are executed within the worker threads. This should be
* threads. This should be noted when working with thread pools. * noted when working with thread pools.
* <p> * <p>
* Java provides its own implementations of async method invocation pattern. FutureTask, * Java provides its own implementations of async method invocation pattern. FutureTask, CompletableFuture
* CompletableFuture and ExecutorService are the real world implementations of this pattern. But due * and ExecutorService are the real world implementations of this pattern. But due to the nature of parallel
* to the nature of parallel programming, the implementations are not trivial. This example does not * programming, the implementations are not trivial. This example does not take all possible scenarios into
* take all possible scenarios into account but rather provides a simple version that helps to * account but rather provides a simple version that helps to understand the pattern.
* understand the pattern.
* *
* @see AsyncResult * @see AsyncResult
* @see AsyncCallback * @see AsyncCallback
@ -33,68 +32,66 @@ import java.util.concurrent.Callable;
*/ */
public class App { public class App {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
// construct a new executor that will run async tasks // construct a new executor that will run async tasks
AsyncExecutor executor = new ThreadAsyncExecutor(); 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 = AsyncResult<Integer> asyncResult4 = executor.startProcess(lazyval(20, 400), callback("Callback result 4"));
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 value to evaluate
* @param delayMillis artificial delay in milliseconds * @param delayMillis artificial delay in milliseconds
* @return new callable for lazy evaluation * @return new callable for lazy evaluation
*/ */
private static <T> Callable<T> lazyval(T value, long delayMillis) { private static <T> Callable<T> lazyval(T value, long delayMillis) {
return () -> { return () -> {
Thread.sleep(delayMillis); Thread.sleep(delayMillis);
log("Task completed with: " + value); log("Task completed with: " + value);
return 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 callback name
* @return new async callback * @return new async callback
*/ */
private static <T> AsyncCallback<T> callback(String name) { private static <T> AsyncCallback<T> callback(String name) {
return (value, ex) -> { return (value, ex) -> {
if (ex.isPresent()) { if (ex.isPresent()) {
log(name + " failed: " + ex.map(Exception::getMessage).orElse("")); log(name + " failed: " + ex.map(Exception::getMessage).orElse(""));
} else { } else {
log(name + ": " + value); 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));
} }
} }

View File

@ -11,11 +11,12 @@ 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);
} }

View File

@ -10,32 +10,33 @@ 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;
} }

View File

@ -10,26 +10,26 @@ import java.util.concurrent.ExecutionException;
*/ */
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;
} }

View File

@ -12,117 +12,116 @@ 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, public <T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException, InterruptedException {
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 or * Simple implementation of async result that allows completing it successfully with a value
* exceptionally with an exception. A really simplified version from its real life cousins * or exceptionally with an 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 any * Sets the value from successful execution and executes callback if available. Notifies
* thread waiting for completion. * any thread waiting for completion.
* *
* @param value value of the evaluated task * @param value value of the evaluated task
*/ */
void setValue(T value) { void setValue(T value) {
this.value = value; this.value = value;
this.state = COMPLETED; this.state = COMPLETED;
this.callback.ifPresent(ac -> ac.onComplete(value, Optional.<Exception>empty())); this.callback.ifPresent(ac -> ac.onComplete(value, Optional.<Exception>empty()));
synchronized (lock) { synchronized (lock) {
lock.notifyAll(); lock.notifyAll();
} }
} }
/** /**
* Sets the exception from failed execution and executes callback if available. Notifies any * Sets the exception from failed execution and executes callback if available. Notifies
* thread waiting for completion. * any thread waiting for completion.
* *
* @param exception exception of the failed task * @param exception exception of the failed task
*/ */
void setException(Exception exception) { void setException(Exception exception) {
this.exception = exception; this.exception = exception;
this.state = FAILED; this.state = FAILED;
this.callback.ifPresent(ac -> ac.onComplete(null, Optional.of(exception))); this.callback.ifPresent(ac -> ac.onComplete(null, Optional.of(exception)));
synchronized (lock) { synchronized (lock) {
lock.notifyAll(); 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();
} }
} }
} }
} }
} }

View File

@ -9,9 +9,10 @@ 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);
} }
} }

View File

@ -4,13 +4,9 @@ title: Bridge
folder: bridge folder: bridge
permalink: /patterns/bridge/ permalink: /patterns/bridge/
categories: Structural categories: Structural
tags: tags: Java
- Java
- Gang Of Four
--- ---
**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.
@ -24,7 +20,3 @@ vary independently.
* changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled. * changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled.
* you have a proliferation of classes. Such a class hierarchy indicates the need for splitting an object into two parts. Rumbaugh uses the term "nested generalizations" to refer to such class hierarchies * you have a proliferation of classes. Such a class hierarchy indicates the need for splitting an object into two parts. Rumbaugh uses the term "nested generalizations" to refer to such class hierarchies
* you want to share an implementation among multiple objects (perhaps using reference counting), and this fact should be hidden from the client. A simple example is Coplien's String class, in which multiple objects can share the same string representation. * you want to share an implementation among multiple objects (perhaps using reference counting), and this fact should be hidden from the client. A simple example is Coplien's String class, in which multiple objects can share the same string representation.
**Credits**
* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612)

View File

@ -1,18 +1,19 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" <project
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
<modelVersion>4.0.0</modelVersion> xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<parent> <modelVersion>4.0.0</modelVersion>
<groupId>com.iluwatar</groupId> <parent>
<artifactId>java-design-patterns</artifactId> <groupId>com.iluwatar</groupId>
<version>1.8.0</version> <artifactId>java-design-patterns</artifactId>
</parent> <version>1.6.0</version>
<artifactId>bridge</artifactId> </parent>
<dependencies> <artifactId>bridge</artifactId>
<dependency> <dependencies>
<groupId>junit</groupId> <dependency>
<artifactId>junit</artifactId> <groupId>junit</groupId>
<scope>test</scope> <artifactId>junit</artifactId>
</dependency> <scope>test</scope>
</dependencies> </dependency>
</dependencies>
</project> </project>

View File

@ -2,38 +2,38 @@ package com.iluwatar.bridge;
/** /**
* *
* The Bridge pattern can also be thought of as two layers of abstraction. With Bridge, you can * In Bridge pattern both abstraction ({@link MagicWeapon}) and implementation
* decouple an abstraction from its implementation so that the two can vary independently. * ({@link MagicWeaponImpl}) have their own class hierarchies. The interface of the
* <p> * implementations can be changed without affecting the clients.
* In Bridge pattern both abstraction ({@link MagicWeapon}) and implementation (
* {@link MagicWeaponImpl}) have their own class hierarchies. The interface of the implementations
* 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) {
public static void main(String[] args) { BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(
BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(new Excalibur()); new Excalibur());
blindingMagicWeapon.wield(); blindingMagicWeapon.wield();
blindingMagicWeapon.blind(); blindingMagicWeapon.blind();
blindingMagicWeapon.swing(); blindingMagicWeapon.swing();
blindingMagicWeapon.unwield(); blindingMagicWeapon.unwield();
FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(new Mjollnir()); FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(
flyingMagicWeapon.wield(); new Mjollnir());
flyingMagicWeapon.fly(); flyingMagicWeapon.wield();
flyingMagicWeapon.swing(); flyingMagicWeapon.fly();
flyingMagicWeapon.unwield(); flyingMagicWeapon.swing();
flyingMagicWeapon.unwield();
SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(new Stormbringer()); SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(
soulEatingMagicWeapon.wield(); new Stormbringer());
soulEatingMagicWeapon.swing(); soulEatingMagicWeapon.wield();
soulEatingMagicWeapon.eatSoul(); soulEatingMagicWeapon.swing();
soulEatingMagicWeapon.unwield(); soulEatingMagicWeapon.eatSoul();
} soulEatingMagicWeapon.unwield();
}
} }

View File

@ -7,31 +7,32 @@ 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();
}
} }

View File

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

View File

@ -7,23 +7,25 @@ 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");
}
} }

View File

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

View File

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

View File

@ -7,19 +7,20 @@ 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;
}
} }

View File

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

View File

@ -7,23 +7,25 @@ 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");
}
} }

View File

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

View File

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

View File

@ -7,23 +7,24 @@ 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");
}
} }

View File

@ -11,9 +11,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);
} }
} }

View File

@ -4,9 +4,7 @@ title: Builder
folder: builder folder: builder
permalink: /patterns/builder/ permalink: /patterns/builder/
categories: Creational categories: Creational
tags: tags: Java
- Java
- Gang Of Four
--- ---
**Intent:** Separate the construction of a complex object from its **Intent:** Separate the construction of a complex object from its
@ -24,7 +22,3 @@ representations.
* [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) * [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html)
* [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) * [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder)
**Credits**
* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612)

View File

@ -1,18 +1,19 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" <project
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
<modelVersion>4.0.0</modelVersion> xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<parent> <modelVersion>4.0.0</modelVersion>
<groupId>com.iluwatar</groupId> <parent>
<artifactId>java-design-patterns</artifactId> <groupId>com.iluwatar</groupId>
<version>1.8.0</version> <artifactId>java-design-patterns</artifactId>
</parent> <version>1.6.0</version>
<artifactId>builder</artifactId> </parent>
<dependencies> <artifactId>builder</artifactId>
<dependency> <dependencies>
<groupId>junit</groupId> <dependency>
<artifactId>junit</artifactId> <groupId>junit</groupId>
<scope>test</scope> <artifactId>junit</artifactId>
</dependency> <scope>test</scope>
</dependencies> </dependency>
</dependencies>
</project> </project>

View File

@ -1,55 +1,42 @@
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 constructor * This is the Builder pattern variation as described by Joshua Bloch in
* anti-pattern. The telescoping constructor anti-pattern occurs when the increase of object * Effective Java 2nd Edition.
* constructor parameter combination leads to an exponential list of constructors. Instead of using
* numerous constructors, the builder pattern uses another object, a builder, that receives each
* initialization parameter step by step 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 flat data (html * We want to build {@link Hero} objects, but its construction is complex because of the
* code, SQL query, X.509 certificate...), that is to say, data that can't be easily edited. This * many parameters needed. To aid the user we introduce {@link HeroBuilder} class.
* type of data cannot be edited step by step and must be edited at once. The best way to construct * {@link HeroBuilder} takes the minimum parameters to build {@link Hero} object in its
* such an object is to use a builder class. * constructor. After that additional configuration for the {@link Hero} object can be
* <p> * done using the fluent {@link HeroBuilder} interface. When configuration is ready the
* In this example we have the Builder pattern variation as described by Joshua Bloch in Effective * build method is called to receive the final {@link Hero} object.
* Java 2nd Edition.
* <p>
* We want to build {@link Hero} objects, but its construction is complex because of the many
* parameters needed. To aid the user we introduce {@link HeroBuilder} class. {@link HeroBuilder}
* takes the minimum parameters to build {@link Hero} object in its constructor. After that
* additional configuration for the {@link Hero} object can be done using the fluent
* {@link HeroBuilder} interface. When configuration is ready the build method is called to receive
* 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 = Hero mage = new HeroBuilder(Profession.MAGE, "Riobard")
new HeroBuilder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK) .withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER)
.withWeapon(Weapon.DAGGER).build(); .build();
System.out.println(mage); System.out.println(mage);
Hero warrior = Hero warrior = new HeroBuilder(Profession.WARRIOR, "Amberjill")
new HeroBuilder(Profession.WARRIOR, "Amberjill").withHairColor(HairColor.BLOND) .withHairColor(HairColor.BLOND)
.withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD) .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL)
.build(); .withWeapon(Weapon.SWORD).build();
System.out.println(warrior); System.out.println(warrior);
Hero thief = Hero thief = new HeroBuilder(Profession.THIEF, "Desmond")
new HeroBuilder(Profession.THIEF, "Desmond").withHairType(HairType.BALD) .withHairType(HairType.BALD).withWeapon(Weapon.BOW).build();
.withWeapon(Weapon.BOW).build(); System.out.println(thief);
System.out.println(thief);
} }
} }

View File

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

View File

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

View File

@ -7,17 +7,16 @@ package com.iluwatar.builder;
*/ */
public enum HairType { public enum HairType {
BALD("bald"), SHORT("short"), CURLY("curly"), LONG_STRAIGHT("long straight"), LONG_CURLY( BALD("bald"), SHORT("short"), CURLY("curly"), LONG_STRAIGHT("long straight"), LONG_CURLY("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;
} }
} }

View File

@ -7,122 +7,123 @@ 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) { public HeroBuilder(Profession profession, String name) {
if (profession == null || name == null) { if (profession == null || name == null) {
throw new IllegalArgumentException("profession and name can not be null"); throw new IllegalArgumentException(
} "profession and name can not be null");
this.profession = profession; }
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);
} }
} }
} }

View File

@ -7,10 +7,11 @@ 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();
}
} }

View File

@ -7,10 +7,11 @@ 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();
}
} }

View File

@ -2,7 +2,7 @@ package com.iluwatar.builder;
import org.junit.Test; import org.junit.Test;
import com.iluwatar.builder.App; import com.iluwatar. builder.App;
/** /**
* *
@ -11,9 +11,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);
} }
} }

View File

@ -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.8.0</version> <version>1.6.0</version>
</parent> </parent>
<artifactId>business-delegate</artifactId> <artifactId>business-delegate</artifactId>
<dependencies> <dependencies>
@ -15,10 +15,5 @@
<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>

View File

@ -1,40 +1,35 @@
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.
* *
* <p>Some of the services the Business Delegate uses are instantiated directly, and some can be * The Business Delegate pattern adds an abstraction layer between the presentation and business tiers.
* retrieved through service lookups. The Business Delegate itself may contain business logic too * By using the pattern we gain loose coupling between the tiers. The Business Delegate encapsulates
* potentially tying together multiple service calls, exception handling, retrying etc. * knowledge about how to locate, connect to, and interact with the business objects that make up
* * the application.
* <p>In this example the client ({@link Client}) utilizes a business delegate ( * <p>
* {@link BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate * Some of the services the Business Delegate uses are instantiated directly, and some can be retrieved
* service and makes the service call. * through service lookups. The Business Delegate itself may contain business logic too potentially tying
* together multiple service calls, exception handling, retrying etc.
* <p>
* In this example the client ({@link Client}) utilizes a business delegate ({@link BusinessDelegate}) to execute a task.
* The Business Delegate then selects the appropriate service and makes the service call.
*
*/ */
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);
* Program entry point. client.doTask();
*
* @param args command line args
*/
public static void main(String[] args) {
BusinessDelegate businessDelegate = new BusinessDelegate(); businessDelegate.setServiceType(ServiceType.JMS);
BusinessLookup businessLookup = new BusinessLookup(); client.doTask();
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();
}
} }

View File

@ -1,24 +1,22 @@
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;
private BusinessLookup lookupService; public void setServiceType(ServiceType serviceType) {
private BusinessService businessService; this.serviceType = serviceType;
private ServiceType serviceType; }
public void setLookupService(BusinessLookup businessLookup) { public void doTask() {
this.lookupService = businessLookup; businessService = lookupService.getBusinessService(serviceType);
} businessService.doProcessing();
}
public void setServiceType(ServiceType serviceType) {
this.serviceType = serviceType;
}
public void doTask() {
businessService = lookupService.getBusinessService(serviceType);
businessService.doProcessing();
}
} }

View File

@ -1,31 +1,17 @@
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 {
private EjbService ejbService; public BusinessService getBusinessService(ServiceType serviceType) {
if (serviceType.equals(ServiceType.EJB)) {
private JmsService jmsService; return new EjbService();
} 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;
}
} }

View File

@ -7,5 +7,5 @@ package com.iluwatar.business.delegate;
*/ */
public interface BusinessService { public interface BusinessService {
void doProcessing(); void doProcessing();
} }

View File

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

View File

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

View File

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

View File

@ -6,6 +6,6 @@ package com.iluwatar.business.delegate;
* *
*/ */
public enum ServiceType { public enum ServiceType {
EJB, JMS; EJB, JMS;
} }

View File

@ -0,0 +1,19 @@
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);
}
}

View File

@ -1,78 +0,0 @@
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();
}
}

1
caching/.gitignore vendored
View File

@ -1 +0,0 @@
/target/

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

View File

@ -1,106 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
realizations="true" associations="true" dependencies="false" nesting-relationships="true">
<class id="1" language="java" name="main.java.com.wssia.caching.App" project="CachingPatterns"
file="/CachingPatterns/src/main/java/com/wssia/caching/App.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="249" y="150"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="2" language="java" name="main.java.com.wssia.caching.AppManager" project="CachingPatterns"
file="/CachingPatterns/src/main/java/com/wssia/caching/AppManager.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="502" y="163"/>
<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="main.java.com.wssia.caching.CacheStore" project="CachingPatterns"
file="/CachingPatterns/src/main/java/com/wssia/caching/CacheStore.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="537" y="436"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<enumeration id="4" language="java" name="main.java.com.wssia.caching.CachingPolicy" project="CachingPatterns"
file="/CachingPatterns/src/main/java/com/wssia/caching/CachingPolicy.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="789" y="162"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</enumeration>
<class id="5" language="java" name="main.java.com.wssia.caching.DBManager" project="CachingPatterns"
file="/CachingPatterns/src/main/java/com/wssia/caching/DBManager.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="1137" y="134"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="6" language="java" name="main.java.com.wssia.caching.LRUCache" project="CachingPatterns"
file="/CachingPatterns/src/main/java/com/wssia/caching/LRUCache.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="884" y="435"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="7" language="java" name="main.java.com.wssia.caching.UserAccount" project="CachingPatterns"
file="/CachingPatterns/src/main/java/com/wssia/caching/UserAccount.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="1140" y="405"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="8" language="java" name="test.java.com.wssia.caching.AppTest" project="CachingPatterns"
file="/CachingPatterns/src/test/java/com/wssia/caching/AppTest.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="251" y="374"/>
<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>
<association id="9">
<end type="SOURCE" refId="2" navigable="false">
<attribute id="10" name="cachingPolicy"/>
<multiplicity id="11" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="4" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="12">
<end type="SOURCE" refId="8" navigable="false">
<attribute id="13" name="app"/>
<multiplicity id="14" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="1" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="15">
<end type="SOURCE" refId="3" navigable="false">
<attribute id="16" name="cache"/>
<multiplicity id="17" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="6" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</classifier-display>
<association-display labels="true" multiplicity="true"/>
</class-diagram>

View File

@ -1,24 +0,0 @@
---
layout: pattern
title: Caching
folder: caching
permalink: /patterns/caching/
categories: Other
tags:
- Java
---
**Intent:** To avoid expensive re-acquisition of resources by not releasing
the resources immediately after their use. The resources retain their identity, are kept in some
fast-access storage, and are re-used to avoid having to acquire them again.
![alt text](./etc/caching.png "Caching")
**Applicability:** Use the Caching pattern(s) when
* Repetitious acquisition, initialization, and release of the same resource causes unnecessary performance overhead.
**Credits**
* [Write-through, write-around, write-back: Cache explained](http://www.computerweekly.com/feature/Write-through-write-around-write-back-Cache-explained)
* [Read-Through, Write-Through, Write-Behind, and Refresh-Ahead Caching](https://docs.oracle.com/cd/E15357_01/coh.360/e15723/cache_rtwtwbra.htm#COHDG5177)

View File

@ -1,51 +0,0 @@
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.8.0</version>
</parent>
<artifactId>caching</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-core</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>3.0.4</version>
</dependency>
</dependencies>
<!--
Due to the use of MongoDB in the test of this pattern, TRAVIS and/or MAVEN might fail if the DB connection is
not open for the JUnit test. To avoid disrupting the compilation process, the surefire plug-in was used
to SKIP the running of the JUnit tests for this pattern. To ACTIVATE the running of the tests, change the
skipTests (below) flag to 'false' and vice-versa.
-->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<configuration>
<skipTests>false</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,117 +0,0 @@
package com.iluwatar.caching;
/**
*
* The Caching pattern describes how to avoid expensive re-acquisition of resources by not releasing
* the resources immediately after their use. The resources retain their identity, are kept in some
* fast-access storage, and are re-used to avoid having to acquire them again. There are three main
* caching strategies/techniques in this pattern; each with their own pros and cons. They are:
* <code>write-through</code> which writes data to the cache and DB in a single transaction,
* <code>write-around</code> which writes data immediately into the DB instead of the cache, and
* <code>write-behind</code> which writes data into the cache initially whilst the data is only
* written into the DB when the cache is full. The <code>read-through</code> strategy is also
* included in the mentioned three strategies -- returns data from the cache to the caller <b>if</b>
* it exists <b>else</b> queries from DB and stores it into the cache for future use. These
* strategies determine when the data in the cache should be written back to the backing store (i.e.
* Database) and help keep both data sources synchronized/up-to-date. This pattern can improve
* performance and also helps to maintain consistency between data held in the cache and the data in
* the underlying data store.
* <p>
* In this example, the user account ({@link UserAccount}) entity is used as the underlying
* application data. The cache itself is implemented as an internal (Java) data structure. It adopts
* a Least-Recently-Used (LRU) strategy for evicting data from itself when its full. The three
* strategies are individually tested. The testing of the cache is restricted towards saving and
* querying of user accounts from the underlying data store ( {@link DBManager}). The main class (
* {@link App} is not aware of the underlying mechanics of the application (i.e. save and query) and
* whether the data is coming from the cache or the DB (i.e. separation of concern). The AppManager
* ({@link AppManager}) handles the transaction of data to-and-from the underlying data store
* (depending on the preferred caching policy/strategy).
*
* <i>App --> AppManager --> CacheStore/LRUCache/CachingPolicy --> DBManager</i>
* </p>
*
* @see CacheStore
* @See LRUCache
* @see CachingPolicy
*
*/
public class App {
/**
* Program entry point
*
* @param args command line args
*/
public static void main(String[] args) {
AppManager.initDB(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests
// and the App class to avoid Maven compilation errors. Set flag to
// true to run the tests with MongoDB (provided that MongoDB is
// installed and socket connection is open).
AppManager.initCacheCapacity(3);
App app = new App();
app.useReadAndWriteThroughStrategy();
app.useReadThroughAndWriteAroundStrategy();
app.useReadThroughAndWriteBehindStrategy();
}
/**
* Read-through and write-through
*/
public void useReadAndWriteThroughStrategy() {
System.out.println("# CachingPolicy.THROUGH");
AppManager.initCachingPolicy(CachingPolicy.THROUGH);
UserAccount userAccount1 = new UserAccount("001", "John", "He is a boy.");
AppManager.save(userAccount1);
System.out.println(AppManager.printCacheContent());
userAccount1 = AppManager.find("001");
userAccount1 = AppManager.find("001");
}
/**
* Read-through and write-around
*/
public void useReadThroughAndWriteAroundStrategy() {
System.out.println("# CachingPolicy.AROUND");
AppManager.initCachingPolicy(CachingPolicy.AROUND);
UserAccount userAccount2 = new UserAccount("002", "Jane", "She is a girl.");
AppManager.save(userAccount2);
System.out.println(AppManager.printCacheContent());
userAccount2 = AppManager.find("002");
System.out.println(AppManager.printCacheContent());
userAccount2 = AppManager.find("002");
userAccount2.setUserName("Jane G.");
AppManager.save(userAccount2);
System.out.println(AppManager.printCacheContent());
userAccount2 = AppManager.find("002");
System.out.println(AppManager.printCacheContent());
userAccount2 = AppManager.find("002");
}
/**
* Read-through and write-behind
*/
public void useReadThroughAndWriteBehindStrategy() {
System.out.println("# CachingPolicy.BEHIND");
AppManager.initCachingPolicy(CachingPolicy.BEHIND);
UserAccount userAccount3 = new UserAccount("003", "Adam", "He likes food.");
UserAccount userAccount4 = new UserAccount("004", "Rita", "She hates cats.");
UserAccount userAccount5 = new UserAccount("005", "Isaac", "He is allergic to mustard.");
AppManager.save(userAccount3);
AppManager.save(userAccount4);
AppManager.save(userAccount5);
System.out.println(AppManager.printCacheContent());
userAccount3 = AppManager.find("003");
System.out.println(AppManager.printCacheContent());
UserAccount userAccount6 = new UserAccount("006", "Yasha", "She is an only child.");
AppManager.save(userAccount6);
System.out.println(AppManager.printCacheContent());
userAccount4 = AppManager.find("004");
System.out.println(AppManager.printCacheContent());
}
}

View File

@ -1,75 +0,0 @@
package com.iluwatar.caching;
import java.text.ParseException;
/**
*
* AppManager helps to bridge the gap in communication between the main class and the application's
* back-end. DB connection is initialized through this class. The chosen caching strategy/policy is
* also initialized here. Before the cache can be used, the size of the cache has to be set.
* Depending on the chosen caching policy, AppManager will call the appropriate function in the
* CacheStore class.
*
*/
public class AppManager {
private static CachingPolicy cachingPolicy;
/**
*
* Developer/Tester is able to choose whether the application should use MongoDB as its underlying
* data storage or a simple Java data structure to (temporarily) store the data/objects during
* runtime.
*/
public static void initDB(boolean useMongoDB) {
if (useMongoDB) {
try {
DBManager.connect();
} catch (ParseException e) {
e.printStackTrace();
}
} else {
DBManager.createVirtualDB();
}
}
public static void initCachingPolicy(CachingPolicy policy) {
cachingPolicy = policy;
if (cachingPolicy == CachingPolicy.BEHIND) {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
CacheStore.flushCache();
}
}));
}
CacheStore.clearCache();
}
public static void initCacheCapacity(int capacity) {
CacheStore.initCapacity(capacity);
}
public static UserAccount find(String userID) {
if (cachingPolicy == CachingPolicy.THROUGH || cachingPolicy == CachingPolicy.AROUND) {
return CacheStore.readThrough(userID);
} else if (cachingPolicy == CachingPolicy.BEHIND) {
return CacheStore.readThroughWithWriteBackPolicy(userID);
}
return null;
}
public static void save(UserAccount userAccount) {
if (cachingPolicy == CachingPolicy.THROUGH) {
CacheStore.writeThrough(userAccount);
} else if (cachingPolicy == CachingPolicy.AROUND) {
CacheStore.writeAround(userAccount);
} else if (cachingPolicy == CachingPolicy.BEHIND) {
CacheStore.writeBehind(userAccount);
}
}
public static String printCacheContent() {
return CacheStore.print();
}
}

View File

@ -1,104 +0,0 @@
package com.iluwatar.caching;
import java.util.ArrayList;
/**
*
* The caching strategies are implemented in this class.
*
*/
public class CacheStore {
static LRUCache cache = null;
public static void initCapacity(int capacity) {
if (null == cache)
cache = new LRUCache(capacity);
else
cache.setCapacity(capacity);
}
public static UserAccount readThrough(String userID) {
if (cache.contains(userID)) {
System.out.println("# Cache Hit!");
return cache.get(userID);
}
System.out.println("# Cache Miss!");
UserAccount userAccount = DBManager.readFromDB(userID);
cache.set(userID, userAccount);
return userAccount;
}
public static void writeThrough(UserAccount userAccount) {
if (cache.contains(userAccount.getUserID())) {
DBManager.updateDB(userAccount);
} else {
DBManager.writeToDB(userAccount);
}
cache.set(userAccount.getUserID(), userAccount);
}
public static void writeAround(UserAccount userAccount) {
if (cache.contains(userAccount.getUserID())) {
DBManager.updateDB(userAccount);
cache.invalidate(userAccount.getUserID()); // Cache data has been updated -- remove older
// version from cache.
} else {
DBManager.writeToDB(userAccount);
}
}
public static UserAccount readThroughWithWriteBackPolicy(String userID) {
if (cache.contains(userID)) {
System.out.println("# Cache Hit!");
return cache.get(userID);
}
System.out.println("# Cache Miss!");
UserAccount userAccount = DBManager.readFromDB(userID);
if (cache.isFull()) {
System.out.println("# Cache is FULL! Writing LRU data to DB...");
UserAccount toBeWrittenToDB = cache.getLRUData();
DBManager.upsertDB(toBeWrittenToDB);
}
cache.set(userID, userAccount);
return userAccount;
}
public static void writeBehind(UserAccount userAccount) {
if (cache.isFull() && !cache.contains(userAccount.getUserID())) {
System.out.println("# Cache is FULL! Writing LRU data to DB...");
UserAccount toBeWrittenToDB = cache.getLRUData();
DBManager.upsertDB(toBeWrittenToDB);
}
cache.set(userAccount.getUserID(), userAccount);
}
public static void clearCache() {
if (null != cache)
cache.clear();
}
/**
* Writes remaining content in the cache into the DB.
*/
public static void flushCache() {
System.out.println("# flushCache...");
if (null == cache)
return;
ArrayList<UserAccount> listOfUserAccounts = cache.getCacheDataInListForm();
for (UserAccount userAccount : listOfUserAccounts) {
DBManager.upsertDB(userAccount);
}
}
public static String print() {
ArrayList<UserAccount> listOfUserAccounts = cache.getCacheDataInListForm();
StringBuilder sb = new StringBuilder();
sb.append("\n--CACHE CONTENT--\n");
for (UserAccount userAccount : listOfUserAccounts) {
sb.append(userAccount.toString() + "\n");
}
sb.append("----\n");
return sb.toString();
}
}

View File

@ -1,20 +0,0 @@
package com.iluwatar.caching;
/**
*
* Enum class containing the three caching strategies implemented in the pattern.
*
*/
public enum CachingPolicy {
THROUGH("through"), AROUND("around"), BEHIND("behind");
private String policy;
private CachingPolicy(String policy) {
this.policy = policy;
}
public String getPolicy() {
return policy;
}
}

View File

@ -1,123 +0,0 @@
package com.iluwatar.caching;
import java.text.ParseException;
import java.util.HashMap;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
/**
*
* <p>DBManager handles the communication with the underlying data store i.e. Database. It contains the
* implemented methods for querying, inserting, and updating data. MongoDB was used as the database
* for the application.</p>
*
* <p>Developer/Tester is able to choose whether the application should use MongoDB as its underlying
* data storage (connect()) or a simple Java data structure to (temporarily) store the data/objects
* during runtime (createVirtualDB()).</p>
*
*/
public class DBManager {
private static MongoClient mongoClient;
private static MongoDatabase db;
private static boolean useMongoDB;
private static HashMap<String, UserAccount> virtualDB;
public static void createVirtualDB() {
useMongoDB = false;
virtualDB = new HashMap<String, UserAccount>();
}
public static void connect() throws ParseException {
useMongoDB = true;
mongoClient = new MongoClient();
db = mongoClient.getDatabase("test");
}
public static UserAccount readFromDB(String userID) {
if (!useMongoDB) {
if (virtualDB.containsKey(userID))
return virtualDB.get(userID);
return null;
}
if (null == db) {
try {
connect();
} catch (ParseException e) {
e.printStackTrace();
}
}
FindIterable<Document> iterable =
db.getCollection("user_accounts").find(new Document("userID", userID));
if (iterable == null)
return null;
Document doc = iterable.first();
UserAccount userAccount =
new UserAccount(userID, doc.getString("userName"), doc.getString("additionalInfo"));
return userAccount;
}
public static void writeToDB(UserAccount userAccount) {
if (!useMongoDB) {
virtualDB.put(userAccount.getUserID(), userAccount);
return;
}
if (null == db) {
try {
connect();
} catch (ParseException e) {
e.printStackTrace();
}
}
db.getCollection("user_accounts").insertOne(
new Document("userID", userAccount.getUserID()).append("userName",
userAccount.getUserName()).append("additionalInfo", userAccount.getAdditionalInfo()));
}
public static void updateDB(UserAccount userAccount) {
if (!useMongoDB) {
virtualDB.put(userAccount.getUserID(), userAccount);
return;
}
if (null == db) {
try {
connect();
} catch (ParseException e) {
e.printStackTrace();
}
}
db.getCollection("user_accounts").updateOne(
new Document("userID", userAccount.getUserID()),
new Document("$set", new Document("userName", userAccount.getUserName()).append(
"additionalInfo", userAccount.getAdditionalInfo())));
}
/**
*
* Insert data into DB if it does not exist. Else, update it.
*/
public static void upsertDB(UserAccount userAccount) {
if (!useMongoDB) {
virtualDB.put(userAccount.getUserID(), userAccount);
return;
}
if (null == db) {
try {
connect();
} catch (ParseException e) {
e.printStackTrace();
}
}
db.getCollection("user_accounts").updateOne(
new Document("userID", userAccount.getUserID()),
new Document("$set", new Document("userID", userAccount.getUserID()).append("userName",
userAccount.getUserName()).append("additionalInfo", userAccount.getAdditionalInfo())),
new UpdateOptions().upsert(true));
}
}

View File

@ -1,146 +0,0 @@
package com.iluwatar.caching;
import java.util.ArrayList;
import java.util.HashMap;
/**
*
* Data structure/implementation of the application's cache. The data structure consists of a hash
* table attached with a doubly linked-list. The linked-list helps in capturing and maintaining the
* LRU data in the cache. When a data is queried (from the cache), added (to the cache), or updated,
* the data is moved to the front of the list to depict itself as the most-recently-used data. The
* LRU data is always at the end of the list.
*
*/
public class LRUCache {
class Node {
String userID;
UserAccount userAccount;
Node previous;
Node next;
public Node(String userID, UserAccount userAccount) {
this.userID = userID;
this.userAccount = userAccount;
}
}
int capacity;
HashMap<String, Node> cache = new HashMap<String, Node>();
Node head = null;
Node end = null;
public LRUCache(int capacity) {
this.capacity = capacity;
}
public UserAccount get(String userID) {
if (cache.containsKey(userID)) {
Node node = cache.get(userID);
remove(node);
setHead(node);
return node.userAccount;
}
return null;
}
/**
*
* Remove node from linked list.
*/
public void remove(Node node) {
if (node.previous != null) {
node.previous.next = node.next;
} else {
head = node.next;
}
if (node.next != null) {
node.next.previous = node.previous;
} else {
end = node.previous;
}
}
/**
*
* Move node to the front of the list.
*/
public void setHead(Node node) {
node.next = head;
node.previous = null;
if (head != null)
head.previous = node;
head = node;
if (end == null)
end = head;
}
public void set(String userID, UserAccount userAccount) {
if (cache.containsKey(userID)) {
Node old = cache.get(userID);
old.userAccount = userAccount;
remove(old);
setHead(old);
} else {
Node newNode = new Node(userID, userAccount);
if (cache.size() >= capacity) {
System.out.println("# Cache is FULL! Removing " + end.userID + " from cache...");
cache.remove(end.userID); // remove LRU data from cache.
remove(end);
setHead(newNode);
} else {
setHead(newNode);
}
cache.put(userID, newNode);
}
}
public boolean contains(String userID) {
return cache.containsKey(userID);
}
public void invalidate(String userID) {
System.out.println("# " + userID + " has been updated! Removing older version from cache...");
Node toBeRemoved = cache.get(userID);
remove(toBeRemoved);
cache.remove(userID);
}
public boolean isFull() {
return cache.size() >= capacity;
}
public UserAccount getLRUData() {
return end.userAccount;
}
public void clear() {
head = null;
end = null;
cache.clear();
}
/**
*
* Returns cache data in list form.
*/
public ArrayList<UserAccount> getCacheDataInListForm() {
ArrayList<UserAccount> listOfCacheData = new ArrayList<UserAccount>();
Node temp = head;
while (temp != null) {
listOfCacheData.add(temp.userAccount);
temp = temp.next;
}
return listOfCacheData;
}
public void setCapacity(int newCapacity) {
if (capacity > newCapacity) {
clear(); // Behavior can be modified to accommodate for decrease in cache size. For now, we'll
// just clear the cache.
} else {
this.capacity = newCapacity;
}
}
}

View File

@ -1,47 +0,0 @@
package com.iluwatar.caching;
/**
*
* Entity class (stored in cache and DB) used in the application.
*
*/
public class UserAccount {
private String userID;
private String userName;
private String additionalInfo;
public UserAccount(String userID, String userName, String additionalInfo) {
this.userID = userID;
this.userName = userName;
this.additionalInfo = additionalInfo;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAdditionalInfo() {
return additionalInfo;
}
public void setAdditionalInfo(String additionalInfo) {
this.additionalInfo = additionalInfo;
}
@Override
public String toString() {
return userID + ", " + userName + ", " + additionalInfo;
}
}

View File

@ -1,41 +0,0 @@
package com.iluwatar.caching;
import org.junit.Before;
import org.junit.Test;
/**
*
* Application test
*
*/
public class AppTest {
App app;
/**
* Setup of application test includes: initializing DB connection and cache size/capacity.
*/
@Before
public void setUp() {
AppManager.initDB(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests
// to avoid Maven compilation errors. Set flag to true to run the
// tests with MongoDB (provided that MongoDB is installed and socket
// connection is open).
AppManager.initCacheCapacity(3);
app = new App();
}
@Test
public void testReadAndWriteThroughStrategy() {
app.useReadAndWriteThroughStrategy();
}
@Test
public void testReadThroughAndWriteAroundStrategy() {
app.useReadThroughAndWriteAroundStrategy();
}
@Test
public void testReadThroughAndWriteBehindStrategy() {
app.useReadThroughAndWriteBehindStrategy();
}
}

View File

@ -1,18 +1,19 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" <project
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
<modelVersion>4.0.0</modelVersion> xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<parent> <modelVersion>4.0.0</modelVersion>
<groupId>com.iluwatar</groupId> <parent>
<artifactId>java-design-patterns</artifactId> <groupId>com.iluwatar</groupId>
<version>1.8.0</version> <artifactId>java-design-patterns</artifactId>
</parent> <version>1.6.0</version>
<artifactId>callback</artifactId> </parent>
<dependencies> <artifactId>callback</artifactId>
<dependency> <dependencies>
<groupId>junit</groupId> <dependency>
<artifactId>junit</artifactId> <groupId>junit</groupId>
<scope>test</scope> <artifactId>junit</artifactId>
</dependency> <scope>test</scope>
</dependencies> </dependency>
</dependencies>
</project> </project>

View File

@ -2,21 +2,20 @@ package com.iluwatar.callback;
/** /**
* *
* Callback pattern is more native for functional languages where functions are treated as * Callback pattern is more native for functional languages where functions are treated as first-class citizens.
* first-class citizens. Prior to Java 8 callbacks can be simulated using simple (alike command) * Prior to Java 8 callbacks can be simulated using simple (alike command) interfaces.
* interfaces.
* *
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
Task task = new SimpleTask(); Task task = new SimpleTask();
Callback callback = new Callback() { Callback callback = new Callback() {
@Override @Override
public void call() { public void call() {
System.out.println("I'm done now."); System.out.println("I'm done now.");
} }
}; };
task.executeWith(callback); task.executeWith(callback);
} }
} }

View File

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

View File

@ -7,8 +7,9 @@ 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.");
} }
} }

View File

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

View File

@ -2,38 +2,18 @@ package com.iluwatar.callback;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import com.iluwatar.callback.App;
/** /**
* Add a field as a counter. Every time the callback method is called increment this field. Unit *
* test checks that the field is being incremented. * Application test
* *
* Could be done with mock objects as well where the call method call is verified.
*/ */
public class AppTest { public class AppTest {
private Integer callingCount = 0; @Test
public void test() {
@Test String[] args = {};
public void test() { App.main(args);
Callback callback = new Callback() { }
@Override
public void call() {
callingCount++;
}
};
Task task = new SimpleTask();
assertEquals("Initial calling count of 0", new Integer(0), callingCount);
task.executeWith(callback);
assertEquals("Callback called once", new Integer(1), callingCount);
task.executeWith(callback);
assertEquals("Callback called twice", new Integer(2), callingCount);
}
} }

View File

@ -4,9 +4,7 @@ title: Chain of responsibility
folder: chain folder: chain
permalink: /patterns/chain/ permalink: /patterns/chain/
categories: Behavioral categories: Behavioral
tags: tags: Java
- Java
- Gang Of Four
--- ---
**Intent:** Avoid coupling the sender of a request to its receiver by giving **Intent:** Avoid coupling the sender of a request to its receiver by giving
@ -25,7 +23,3 @@ objects and pass the request along the chain until an object handles it.
* [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29) * [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29)
* [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html) * [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html)
**Credits**
* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612)

View File

@ -1,18 +1,19 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" <project
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
<modelVersion>4.0.0</modelVersion> xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<parent> <modelVersion>4.0.0</modelVersion>
<groupId>com.iluwatar</groupId> <parent>
<artifactId>java-design-patterns</artifactId> <groupId>com.iluwatar</groupId>
<version>1.8.0</version> <artifactId>java-design-patterns</artifactId>
</parent> <version>1.6.0</version>
<artifactId>chain</artifactId> </parent>
<dependencies> <artifactId>chain</artifactId>
<dependency> <dependencies>
<groupId>junit</groupId> <dependency>
<artifactId>junit</artifactId> <groupId>junit</groupId>
<scope>test</scope> <artifactId>junit</artifactId>
</dependency> <scope>test</scope>
</dependencies> </dependency>
</dependencies>
</project> </project>

View File

@ -2,30 +2,25 @@ package com.iluwatar.chain;
/** /**
* *
* The Chain of Responsibility pattern is a design pattern consisting of command objects and a * Chain of Responsibility organizes request handlers ({@link RequestHandler}) into a
* series of processing objects. Each processing object contains logic that defines the types of * chain where each handler has a chance to act on the request on its turn. In
* command objects that it can handle; the rest are passed to the next processing object in the * this example the king ({@link OrcKing}) makes requests and the military orcs
* chain. A mechanism also exists for adding new processing objects to the end of this chain. * ({@link OrcCommander}, {@link OrcOfficer}, {@link OrcSoldier}) form the handler chain.
* <p>
* In this example we organize the request handlers ({@link RequestHandler}) into a chain where each
* handler has a chance to act on the request on its turn. Here the king ({@link OrcKing}) makes
* requests and the military orcs ({@link OrcCommander}, {@link OrcOfficer}, {@link OrcSoldier})
* form the handler chain.
* *
*/ */
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) {
OrcKing king = new OrcKing(); OrcKing king = new OrcKing();
king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle"));
king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); king.makeRequest(new Request(RequestType.TORTURE_PRISONER,
king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); "torture prisoner"));
king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax"));
} }
} }

View File

@ -7,21 +7,21 @@ package com.iluwatar.chain;
*/ */
public class OrcCommander extends RequestHandler { public class OrcCommander extends RequestHandler {
public OrcCommander(RequestHandler handler) { public OrcCommander(RequestHandler handler) {
super(handler); super(handler);
} }
@Override @Override
public void handleRequest(Request req) { public void handleRequest(Request req) {
if (req.getRequestType().equals(RequestType.DEFEND_CASTLE)) { if (req.getRequestType().equals(RequestType.DEFEND_CASTLE)) {
printHandling(req); printHandling(req);
} else { } else {
super.handleRequest(req); super.handleRequest(req);
} }
} }
@Override @Override
public String toString() { public String toString() {
return "Orc commander"; return "Orc commander";
} }
} }

View File

@ -7,18 +7,18 @@ package com.iluwatar.chain;
*/ */
public class OrcKing { public class OrcKing {
RequestHandler chain; RequestHandler chain;
public OrcKing() { public OrcKing() {
buildChain(); buildChain();
} }
private void buildChain() { private void buildChain() {
chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null))); chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null)));
} }
public void makeRequest(Request req) { public void makeRequest(Request req) {
chain.handleRequest(req); chain.handleRequest(req);
} }
} }

View File

@ -7,22 +7,22 @@ package com.iluwatar.chain;
*/ */
public class OrcOfficer extends RequestHandler { public class OrcOfficer extends RequestHandler {
public OrcOfficer(RequestHandler handler) { public OrcOfficer(RequestHandler handler) {
super(handler); super(handler);
} }
@Override @Override
public void handleRequest(Request req) { public void handleRequest(Request req) {
if (req.getRequestType().equals(RequestType.TORTURE_PRISONER)) { if (req.getRequestType().equals(RequestType.TORTURE_PRISONER)) {
printHandling(req); printHandling(req);
} else { } else {
super.handleRequest(req); super.handleRequest(req);
} }
} }
@Override @Override
public String toString() { public String toString() {
return "Orc officer"; return "Orc officer";
} }
} }

View File

@ -7,21 +7,21 @@ package com.iluwatar.chain;
*/ */
public class OrcSoldier extends RequestHandler { public class OrcSoldier extends RequestHandler {
public OrcSoldier(RequestHandler handler) { public OrcSoldier(RequestHandler handler) {
super(handler); super(handler);
} }
@Override @Override
public void handleRequest(Request req) { public void handleRequest(Request req) {
if (req.getRequestType().equals(RequestType.COLLECT_TAX)) { if (req.getRequestType().equals(RequestType.COLLECT_TAX)) {
printHandling(req); printHandling(req);
} else { } else {
super.handleRequest(req); super.handleRequest(req);
} }
} }
@Override @Override
public String toString() { public String toString() {
return "Orc soldier"; return "Orc soldier";
} }
} }

View File

@ -7,32 +7,32 @@ package com.iluwatar.chain;
*/ */
public class Request { public class Request {
private String requestDescription; private String requestDescription;
private RequestType requestType; private RequestType requestType;
public Request(RequestType requestType, String requestDescription) { public Request(RequestType requestType, String requestDescription) {
this.setRequestType(requestType); this.setRequestType(requestType);
this.setRequestDescription(requestDescription); this.setRequestDescription(requestDescription);
} }
public String getRequestDescription() { public String getRequestDescription() {
return requestDescription; return requestDescription;
} }
public void setRequestDescription(String requestDescription) { public void setRequestDescription(String requestDescription) {
this.requestDescription = requestDescription; this.requestDescription = requestDescription;
} }
public RequestType getRequestType() { public RequestType getRequestType() {
return requestType; return requestType;
} }
public void setRequestType(RequestType requestType) { public void setRequestType(RequestType requestType) {
this.requestType = requestType; this.requestType = requestType;
} }
@Override @Override
public String toString() { public String toString() {
return getRequestDescription(); return getRequestDescription();
} }
} }

View File

@ -7,22 +7,22 @@ package com.iluwatar.chain;
*/ */
public abstract class RequestHandler { public abstract class RequestHandler {
private RequestHandler next; private RequestHandler next;
public RequestHandler(RequestHandler next) { public RequestHandler(RequestHandler next) {
this.next = next; this.next = next;
} }
public void handleRequest(Request req) { public void handleRequest(Request req) {
if (next != null) { if (next != null) {
next.handleRequest(req); next.handleRequest(req);
} }
} }
protected void printHandling(Request req) { protected void printHandling(Request req) {
System.out.println(this + " handling request \"" + req + "\""); System.out.println(this + " handling request \"" + req + "\"");
} }
@Override @Override
public abstract String toString(); public abstract String toString();
} }

View File

@ -7,6 +7,6 @@ package com.iluwatar.chain;
*/ */
public enum RequestType { public enum RequestType {
DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX
} }

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