diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java index 618b98c52..5b93f0e46 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java @@ -3,80 +3,78 @@ package com.iluwatar.abstractfactory; /** * - * The Abstract Factory pattern provides a way to encapsulate a group of individual - * factories that have a common theme without specifying their concrete classes. In - * normal usage, the client software creates a concrete implementation of the abstract - * factory and then uses the generic interface of the factory to create the concrete - * objects that are part of the theme. The client does not know (or care) which - * concrete objects it gets from each of these internal factories, since it uses only - * the generic interfaces of their products. This pattern separates the details of - * implementation of a set of objects from their general usage and relies on object - * composition, as object creation is implemented in methods exposed in the factory - * interface. + * The Abstract Factory pattern provides a way to encapsulate a group of individual factories that + * have a common theme without specifying their concrete classes. In normal usage, the client + * software creates a concrete implementation of the abstract factory and then uses the generic + * interface of the factory to create the concrete objects that are part of the theme. The client + * does not know (or care) which concrete objects it gets from each of these internal factories, + * since it uses only the generic interfaces of their products. This pattern separates the details + * of implementation of a set of objects from their general usage and relies on object composition, + * as object creation is implemented in methods exposed in the factory interface. *
- * The essence of the Abstract Factory pattern is a factory interface - * ({@link KingdomFactory}) and its implementations ({@link ElfKingdomFactory}, - * {@link OrcKingdomFactory}). The example uses both concrete implementations to - * create a king, a castle and an army. + * The essence of the Abstract Factory pattern is a factory interface ({@link KingdomFactory}) and + * its implementations ({@link ElfKingdomFactory}, {@link OrcKingdomFactory}). The example uses both + * concrete implementations to create a king, a castle and an army. * */ public class App { - private King king; - private Castle castle; - private Army army; + private King king; + private Castle castle; + private Army army; - /** - * Creates kingdom - * @param factory - */ - public void createKingdom(final KingdomFactory factory) { - setKing(factory.createKing()); - setCastle(factory.createCastle()); - setArmy(factory.createArmy()); - } - - ElfKingdomFactory getElfKingdomFactory() { - return new ElfKingdomFactory(); - } - - OrcKingdomFactory getOrcKingdomFactory() { - return new OrcKingdomFactory(); - } - - King getKing(final KingdomFactory factory) { - return factory.createKing(); - } - - Castle getCastle(final KingdomFactory factory) { - return factory.createCastle(); - } - - Army getArmy(final KingdomFactory factory) { - return factory.createArmy(); - } - - public King getKing() { - return king; - } - - private void setKing(final King king) { - this.king = king; - } - - public Castle getCastle() { - return castle; - } - - private void setCastle(final Castle castle) { - this.castle = castle; - } - - public Army getArmy() { - return army; - } - - private void setArmy(final Army army) { - this.army = army; - } + /** + * Creates kingdom + * + * @param factory + */ + public void createKingdom(final KingdomFactory factory) { + setKing(factory.createKing()); + setCastle(factory.createCastle()); + setArmy(factory.createArmy()); + } + + ElfKingdomFactory getElfKingdomFactory() { + return new ElfKingdomFactory(); + } + + OrcKingdomFactory getOrcKingdomFactory() { + return new OrcKingdomFactory(); + } + + King getKing(final KingdomFactory factory) { + return factory.createKing(); + } + + Castle getCastle(final KingdomFactory factory) { + return factory.createCastle(); + } + + Army getArmy(final KingdomFactory factory) { + return factory.createArmy(); + } + + public King getKing() { + return king; + } + + private void setKing(final King king) { + this.king = king; + } + + public Castle getCastle() { + return castle; + } + + private void setCastle(final Castle castle) { + this.castle = castle; + } + + public Army getArmy() { + return army; + } + + private void setArmy(final Army army) { + this.army = army; + } } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java index 333b5c2cd..8e97d3f4e 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java @@ -7,5 +7,5 @@ package com.iluwatar.abstractfactory; */ public interface Army { - String getDescription(); + String getDescription(); } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java index 0290cb67c..3a36513bf 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java @@ -7,5 +7,5 @@ package com.iluwatar.abstractfactory; */ public interface Castle { - String getDescription(); + String getDescription(); } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java index 410f46951..d7ae734d2 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java @@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory; */ public class ElfArmy implements Army { - static final String DESCRIPTION = "This is the Elven Army!"; + static final String DESCRIPTION = "This is the Elven Army!"; - @Override - public String getDescription() { - return DESCRIPTION; - } + @Override + public String getDescription() { + return DESCRIPTION; + } } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java index fe2e9a0e7..e53b198d7 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java @@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory; */ public class ElfCastle implements Castle { - static final String DESCRIPTION = "This is the Elven castle!"; + static final String DESCRIPTION = "This is the Elven castle!"; - @Override - public String getDescription() { - return DESCRIPTION; - } + @Override + public String getDescription() { + return DESCRIPTION; + } } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java index 66571ee01..36669f42f 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java @@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory; */ public class ElfKing implements King { - static final String DESCRIPTION = "This is the Elven king!"; - - @Override - public String getDescription() { - return DESCRIPTION; - } + static final String DESCRIPTION = "This is the Elven king!"; + + @Override + public String getDescription() { + return DESCRIPTION; + } } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java index 0d62fa5f2..7c8435056 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java @@ -7,16 +7,16 @@ package com.iluwatar.abstractfactory; */ public class ElfKingdomFactory implements KingdomFactory { - public Castle createCastle() { - return new ElfCastle(); - } + public Castle createCastle() { + return new ElfCastle(); + } - public King createKing() { - return new ElfKing(); - } + public King createKing() { + return new ElfKing(); + } - public Army createArmy() { - return new ElfArmy(); - } + public Army createArmy() { + return new ElfArmy(); + } } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java index c7b9a867c..38e6b9f4d 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java @@ -7,5 +7,5 @@ package com.iluwatar.abstractfactory; */ public interface King { - String getDescription(); + String getDescription(); } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java index 00bcd1755..e303b32f4 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java @@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory; */ public interface KingdomFactory { - Castle createCastle(); + Castle createCastle(); - King createKing(); + King createKing(); - Army createArmy(); + Army createArmy(); } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java index 108700511..de16e5007 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java @@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory; */ public class OrcArmy implements Army { - static final String DESCRIPTION = "This is the Orc Army!"; + static final String DESCRIPTION = "This is the Orc Army!"; - @Override - public String getDescription() { - return DESCRIPTION; - } + @Override + public String getDescription() { + return DESCRIPTION; + } } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java index 5012f9200..b355744ce 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java @@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory; */ public class OrcCastle implements Castle { - static final String DESCRIPTION = "This is the Orc castle!"; + static final String DESCRIPTION = "This is the Orc castle!"; - @Override - public String getDescription() { - return DESCRIPTION; - } + @Override + public String getDescription() { + return DESCRIPTION; + } } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKing.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKing.java index a5657d4e4..eac96913f 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKing.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKing.java @@ -7,10 +7,10 @@ package com.iluwatar.abstractfactory; */ public class OrcKing implements King { -static final String DESCRIPTION = "This is the Orc king!"; - - @Override - public String getDescription() { - return DESCRIPTION; - } + static final String DESCRIPTION = "This is the Orc king!"; + + @Override + public String getDescription() { + return DESCRIPTION; + } } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java index 4fdea6656..18301c955 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java @@ -7,16 +7,15 @@ package com.iluwatar.abstractfactory; */ public class OrcKingdomFactory implements KingdomFactory { - public Castle createCastle() { - return new OrcCastle(); - } + public Castle createCastle() { + return new OrcCastle(); + } - public King createKing() { - return new OrcKing(); - } - - public Army createArmy() { - return new OrcArmy(); - } + public King createKing() { + return new OrcKing(); + } + public Army createArmy() { + return new OrcArmy(); + } } diff --git a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java index 4d3659245..5e3869fc8 100644 --- a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java +++ b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java @@ -1,4 +1,5 @@ package com.iluwatar.abstractfactory; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -7,71 +8,71 @@ import org.junit.Test; public class AppTest { - private App app = new App(); - private KingdomFactory elfFactory; - private KingdomFactory orcFactory; - - @Before - public void setUp() { - elfFactory = app.getElfKingdomFactory(); - orcFactory = app.getOrcKingdomFactory(); - } - - @Test - public void king() { - final King elfKing = app.getKing(elfFactory); - assertTrue(elfKing instanceof ElfKing); - assertEquals(ElfKing.DESCRIPTION, elfKing.getDescription()); - final King orcKing = app.getKing(orcFactory); - assertTrue(orcKing instanceof OrcKing); - assertEquals(OrcKing.DESCRIPTION, orcKing.getDescription()); - } - - @Test - public void castle() { - final Castle elfCastle = app.getCastle(elfFactory); - assertTrue(elfCastle instanceof ElfCastle); - assertEquals(ElfCastle.DESCRIPTION, elfCastle.getDescription()); - final Castle orcCastle = app.getCastle(orcFactory); - assertTrue(orcCastle instanceof OrcCastle); - assertEquals(OrcCastle.DESCRIPTION, orcCastle.getDescription()); - } - - @Test - public void army() { - final Army elfArmy = app.getArmy(elfFactory); - assertTrue(elfArmy instanceof ElfArmy); - assertEquals(ElfArmy.DESCRIPTION, elfArmy.getDescription()); - final Army orcArmy = app.getArmy(orcFactory); - assertTrue(orcArmy instanceof OrcArmy); - assertEquals(OrcArmy.DESCRIPTION, orcArmy.getDescription()); - } - - @Test - public void createElfKingdom() { - app.createKingdom(elfFactory); - final King king = app.getKing(); - final Castle castle = app.getCastle(); - final Army army = app.getArmy(); - assertTrue(king instanceof ElfKing); - assertEquals(ElfKing.DESCRIPTION, king.getDescription()); - assertTrue(castle instanceof ElfCastle); - assertEquals(ElfCastle.DESCRIPTION, castle.getDescription()); - assertTrue(army instanceof ElfArmy); - assertEquals(ElfArmy.DESCRIPTION, army.getDescription()); - } - - @Test - public void createOrcKingdom() { - app.createKingdom(orcFactory); - final King king = app.getKing(); - final Castle castle = app.getCastle(); - final Army army = app.getArmy(); - assertTrue(king instanceof OrcKing); - assertEquals(OrcKing.DESCRIPTION, king.getDescription()); - assertTrue(castle instanceof OrcCastle); - assertEquals(OrcCastle.DESCRIPTION, castle.getDescription()); - assertTrue(army instanceof OrcArmy); - assertEquals(OrcArmy.DESCRIPTION, army.getDescription()); - } + private App app = new App(); + private KingdomFactory elfFactory; + private KingdomFactory orcFactory; + + @Before + public void setUp() { + elfFactory = app.getElfKingdomFactory(); + orcFactory = app.getOrcKingdomFactory(); + } + + @Test + public void king() { + final King elfKing = app.getKing(elfFactory); + assertTrue(elfKing instanceof ElfKing); + assertEquals(ElfKing.DESCRIPTION, elfKing.getDescription()); + final King orcKing = app.getKing(orcFactory); + assertTrue(orcKing instanceof OrcKing); + assertEquals(OrcKing.DESCRIPTION, orcKing.getDescription()); + } + + @Test + public void castle() { + final Castle elfCastle = app.getCastle(elfFactory); + assertTrue(elfCastle instanceof ElfCastle); + assertEquals(ElfCastle.DESCRIPTION, elfCastle.getDescription()); + final Castle orcCastle = app.getCastle(orcFactory); + assertTrue(orcCastle instanceof OrcCastle); + assertEquals(OrcCastle.DESCRIPTION, orcCastle.getDescription()); + } + + @Test + public void army() { + final Army elfArmy = app.getArmy(elfFactory); + assertTrue(elfArmy instanceof ElfArmy); + assertEquals(ElfArmy.DESCRIPTION, elfArmy.getDescription()); + final Army orcArmy = app.getArmy(orcFactory); + assertTrue(orcArmy instanceof OrcArmy); + assertEquals(OrcArmy.DESCRIPTION, orcArmy.getDescription()); + } + + @Test + public void createElfKingdom() { + app.createKingdom(elfFactory); + final King king = app.getKing(); + final Castle castle = app.getCastle(); + final Army army = app.getArmy(); + assertTrue(king instanceof ElfKing); + assertEquals(ElfKing.DESCRIPTION, king.getDescription()); + assertTrue(castle instanceof ElfCastle); + assertEquals(ElfCastle.DESCRIPTION, castle.getDescription()); + assertTrue(army instanceof ElfArmy); + assertEquals(ElfArmy.DESCRIPTION, army.getDescription()); + } + + @Test + public void createOrcKingdom() { + app.createKingdom(orcFactory); + final King king = app.getKing(); + final Castle castle = app.getCastle(); + final Army army = app.getArmy(); + assertTrue(king instanceof OrcKing); + assertEquals(OrcKing.DESCRIPTION, king.getDescription()); + assertTrue(castle instanceof OrcCastle); + assertEquals(OrcCastle.DESCRIPTION, castle.getDescription()); + assertTrue(army instanceof OrcArmy); + assertEquals(OrcArmy.DESCRIPTION, army.getDescription()); + } } diff --git a/adapter/src/main/java/com/iluwatar/adapter/App.java b/adapter/src/main/java/com/iluwatar/adapter/App.java index ed036b391..f912efb03 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/App.java +++ b/adapter/src/main/java/com/iluwatar/adapter/App.java @@ -2,30 +2,29 @@ package com.iluwatar.adapter; /** * - * An adapter helps two incompatible interfaces to work together. This is the real - * world definition for an adapter. Interfaces may be incompatible but the inner - * functionality should suit the need. The Adapter design pattern allows otherwise - * incompatible classes to work together by converting the interface of one class - * into an interface expected by the clients. + * An adapter helps two incompatible interfaces to work together. This is the real world definition + * for an adapter. Interfaces may be incompatible but the inner functionality should suit the need. + * The Adapter design pattern allows otherwise incompatible classes to work together by converting + * the interface of one class into an interface expected by the clients. *
- * 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. + * 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. *
- * The Adapter ({@link GnomeEngineer}) converts the interface of the target class
- * ({@link GoblinGlider}) into a suitable one expected by the client
- * ({@link GnomeEngineeringManager}).
+ * 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 {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- Engineer manager = new GnomeEngineeringManager();
- manager.operateDevice();
- }
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ Engineer manager = new GnomeEngineeringManager();
+ manager.operateDevice();
+ }
}
diff --git a/adapter/src/main/java/com/iluwatar/adapter/Engineer.java b/adapter/src/main/java/com/iluwatar/adapter/Engineer.java
index 7478b5b69..a973cb530 100644
--- a/adapter/src/main/java/com/iluwatar/adapter/Engineer.java
+++ b/adapter/src/main/java/com/iluwatar/adapter/Engineer.java
@@ -7,6 +7,5 @@ package com.iluwatar.adapter;
*/
public interface Engineer {
- void operateDevice();
-
+ void operateDevice();
}
diff --git a/adapter/src/main/java/com/iluwatar/adapter/GnomeEngineer.java b/adapter/src/main/java/com/iluwatar/adapter/GnomeEngineer.java
index 35cbc9573..70e166ac3 100644
--- a/adapter/src/main/java/com/iluwatar/adapter/GnomeEngineer.java
+++ b/adapter/src/main/java/com/iluwatar/adapter/GnomeEngineer.java
@@ -2,23 +2,22 @@ package com.iluwatar.adapter;
/**
*
- * Adapter class. Adapts the interface of the device ({@link GoblinGlider}) into
- * {@link Engineer} interface expected by the client ({@link GnomeEngineeringManager}).
+ * Adapter class. Adapts the interface of the device ({@link GoblinGlider}) into {@link Engineer}
+ * interface expected by the client ({@link GnomeEngineeringManager}).
*
*/
public class GnomeEngineer implements Engineer {
- private GoblinGlider glider;
+ private GoblinGlider glider;
- public GnomeEngineer() {
- glider = new GoblinGlider();
- }
-
- @Override
- public void operateDevice() {
- glider.attachGlider();
- glider.gainSpeed();
- glider.takeOff();
- }
+ public GnomeEngineer() {
+ glider = new GoblinGlider();
+ }
+ @Override
+ public void operateDevice() {
+ glider.attachGlider();
+ glider.gainSpeed();
+ glider.takeOff();
+ }
}
diff --git a/adapter/src/main/java/com/iluwatar/adapter/GnomeEngineeringManager.java b/adapter/src/main/java/com/iluwatar/adapter/GnomeEngineeringManager.java
index d95065b88..a2faf1e54 100644
--- a/adapter/src/main/java/com/iluwatar/adapter/GnomeEngineeringManager.java
+++ b/adapter/src/main/java/com/iluwatar/adapter/GnomeEngineeringManager.java
@@ -7,14 +7,14 @@ package com.iluwatar.adapter;
*/
public class GnomeEngineeringManager implements Engineer {
- private Engineer engineer;
+ private Engineer engineer;
- public GnomeEngineeringManager() {
- engineer = new GnomeEngineer();
- }
+ public GnomeEngineeringManager() {
+ engineer = new GnomeEngineer();
+ }
- @Override
- public void operateDevice() {
- engineer.operateDevice();
- }
+ @Override
+ public void operateDevice() {
+ engineer.operateDevice();
+ }
}
diff --git a/adapter/src/main/java/com/iluwatar/adapter/GoblinGlider.java b/adapter/src/main/java/com/iluwatar/adapter/GoblinGlider.java
index ff1dbeb8d..79a9acef6 100644
--- a/adapter/src/main/java/com/iluwatar/adapter/GoblinGlider.java
+++ b/adapter/src/main/java/com/iluwatar/adapter/GoblinGlider.java
@@ -7,15 +7,15 @@ package com.iluwatar.adapter;
*/
public class GoblinGlider {
- public void attachGlider() {
- System.out.println("Glider attached.");
- }
+ public void attachGlider() {
+ System.out.println("Glider attached.");
+ }
- public void gainSpeed() {
- System.out.println("Gaining speed.");
- }
+ public void gainSpeed() {
+ System.out.println("Gaining speed.");
+ }
- public void takeOff() {
- System.out.println("Lift-off!");
- }
+ public void takeOff() {
+ System.out.println("Lift-off!");
+ }
}
diff --git a/adapter/src/test/java/com/iluwatar/adapter/AppTest.java b/adapter/src/test/java/com/iluwatar/adapter/AppTest.java
index 3d877815a..a7462bd9a 100644
--- a/adapter/src/test/java/com/iluwatar/adapter/AppTest.java
+++ b/adapter/src/test/java/com/iluwatar/adapter/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.adapter.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java
index 688d8482f..0b8ee3649 100644
--- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java
+++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java
@@ -4,23 +4,24 @@ import java.util.concurrent.Callable;
/**
* This application demonstrates the async method invocation pattern. Key parts of the pattern are
- * AsyncResult
which is an intermediate container for an asynchronously evaluated value,
- * AsyncCallback
which can be provided to be executed on task completion and
+ * AsyncResult
which is an intermediate container for an asynchronously evaluated
+ * value, AsyncCallback
which can be provided to be executed on task completion and
* AsyncExecutor
that manages the execution of the async tasks.
*
- * The main method shows example flow of async invocations. The main thread starts multiple tasks with - * variable durations and then continues its own work. When the main thread has done it's job it collects - * the results of the async tasks. Two of the tasks are handled with callbacks, meaning the callbacks are - * executed immediately when the tasks complete. + * The main method shows example flow of async invocations. The main thread starts multiple tasks + * with variable durations and then continues its own work. When the main thread has done it's job + * it collects the results of the async tasks. Two of the tasks are handled with callbacks, meaning + * the callbacks are executed immediately when the tasks complete. *
- * Noteworthy difference of thread usage between the async results and callbacks is that the async results - * are collected in the main thread but the callbacks are executed within the worker threads. This should be - * noted when working with thread pools. + * Noteworthy difference of thread usage between the async results and callbacks is that the async + * results are collected in the main thread but the callbacks are executed within the worker + * threads. This should be noted when working with thread pools. *
- * Java provides its own implementations of async method invocation pattern. FutureTask, CompletableFuture
- * and ExecutorService are the real world implementations of this pattern. But due to the nature of parallel
- * programming, the implementations are not trivial. This example does not take all possible scenarios into
- * account but rather provides a simple version that helps to understand the pattern.
+ * Java provides its own implementations of async method invocation pattern. FutureTask,
+ * CompletableFuture and ExecutorService are the real world implementations of this pattern. But due
+ * to the nature of parallel programming, the implementations are not trivial. This example does not
+ * take all possible scenarios into account but rather provides a simple version that helps to
+ * understand the pattern.
*
* @see AsyncResult
* @see AsyncCallback
@@ -32,66 +33,68 @@ import java.util.concurrent.Callable;
*/
public class App {
- public static void main(String[] args) throws Exception {
- // construct a new executor that will run async tasks
- AsyncExecutor executor = new ThreadAsyncExecutor();
+ public static void main(String[] args) throws Exception {
+ // construct a new executor that will run async tasks
+ AsyncExecutor executor = new ThreadAsyncExecutor();
- // start few async tasks with varying processing times, two last with callback handlers
- AsyncResult
- * 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.
+ * 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 {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(
- new Excalibur());
- blindingMagicWeapon.wield();
- blindingMagicWeapon.blind();
- blindingMagicWeapon.swing();
- blindingMagicWeapon.unwield();
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(new Excalibur());
+ blindingMagicWeapon.wield();
+ blindingMagicWeapon.blind();
+ blindingMagicWeapon.swing();
+ blindingMagicWeapon.unwield();
- FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(
- new Mjollnir());
- flyingMagicWeapon.wield();
- flyingMagicWeapon.fly();
- flyingMagicWeapon.swing();
- flyingMagicWeapon.unwield();
+ FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(new Mjollnir());
+ flyingMagicWeapon.wield();
+ flyingMagicWeapon.fly();
+ flyingMagicWeapon.swing();
+ flyingMagicWeapon.unwield();
- SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(
- new Stormbringer());
- soulEatingMagicWeapon.wield();
- soulEatingMagicWeapon.swing();
- soulEatingMagicWeapon.eatSoul();
- soulEatingMagicWeapon.unwield();
-
- }
+ SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(new Stormbringer());
+ soulEatingMagicWeapon.wield();
+ soulEatingMagicWeapon.swing();
+ soulEatingMagicWeapon.eatSoul();
+ soulEatingMagicWeapon.unwield();
+ }
}
diff --git a/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeapon.java b/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeapon.java
index bf4bac8f9..572db251b 100644
--- a/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeapon.java
+++ b/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeapon.java
@@ -7,32 +7,31 @@ package com.iluwatar.bridge;
*/
public class BlindingMagicWeapon extends MagicWeapon {
- public BlindingMagicWeapon(BlindingMagicWeaponImpl imp) {
- super(imp);
- }
+ public BlindingMagicWeapon(BlindingMagicWeaponImpl imp) {
+ super(imp);
+ }
- @Override
- public BlindingMagicWeaponImpl getImp() {
- return (BlindingMagicWeaponImpl) imp;
- }
+ @Override
+ public BlindingMagicWeaponImpl getImp() {
+ return (BlindingMagicWeaponImpl) imp;
+ }
- @Override
- public void wield() {
- getImp().wieldImp();
- }
+ @Override
+ public void wield() {
+ getImp().wieldImp();
+ }
- @Override
- public void swing() {
- getImp().swingImp();
- }
+ @Override
+ public void swing() {
+ getImp().swingImp();
+ }
- @Override
- public void unwield() {
- getImp().unwieldImp();
- }
-
- public void blind() {
- getImp().blindImp();
- }
+ @Override
+ public void unwield() {
+ getImp().unwieldImp();
+ }
+ public void blind() {
+ getImp().blindImp();
+ }
}
diff --git a/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeaponImpl.java b/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeaponImpl.java
index 31dffb042..cf1b47e9a 100644
--- a/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeaponImpl.java
+++ b/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeaponImpl.java
@@ -7,6 +7,6 @@ package com.iluwatar.bridge;
*/
public abstract class BlindingMagicWeaponImpl extends MagicWeaponImpl {
- public abstract void blindImp();
+ public abstract void blindImp();
}
diff --git a/bridge/src/main/java/com/iluwatar/bridge/Excalibur.java b/bridge/src/main/java/com/iluwatar/bridge/Excalibur.java
index 9f7078139..39365eaf8 100644
--- a/bridge/src/main/java/com/iluwatar/bridge/Excalibur.java
+++ b/bridge/src/main/java/com/iluwatar/bridge/Excalibur.java
@@ -7,25 +7,23 @@ package com.iluwatar.bridge;
*/
public class Excalibur extends BlindingMagicWeaponImpl {
- @Override
- public void wieldImp() {
- System.out.println("wielding Excalibur");
- }
+ @Override
+ public void wieldImp() {
+ System.out.println("wielding Excalibur");
+ }
- @Override
- public void swingImp() {
- System.out.println("swinging Excalibur");
- }
+ @Override
+ public void swingImp() {
+ System.out.println("swinging Excalibur");
+ }
- @Override
- public void unwieldImp() {
- System.out.println("unwielding Excalibur");
- }
-
- @Override
- public void blindImp() {
- System.out
- .println("bright light streams from Excalibur blinding the enemy");
- }
+ @Override
+ public void unwieldImp() {
+ System.out.println("unwielding Excalibur");
+ }
+ @Override
+ public void blindImp() {
+ System.out.println("bright light streams from Excalibur blinding the enemy");
+ }
}
diff --git a/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeapon.java b/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeapon.java
index 542e7d97e..b4ae9a8f8 100644
--- a/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeapon.java
+++ b/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeapon.java
@@ -7,31 +7,31 @@ package com.iluwatar.bridge;
*/
public class FlyingMagicWeapon extends MagicWeapon {
- public FlyingMagicWeapon(FlyingMagicWeaponImpl imp) {
- super(imp);
- }
+ public FlyingMagicWeapon(FlyingMagicWeaponImpl imp) {
+ super(imp);
+ }
- public FlyingMagicWeaponImpl getImp() {
- return (FlyingMagicWeaponImpl) imp;
- }
+ public FlyingMagicWeaponImpl getImp() {
+ return (FlyingMagicWeaponImpl) imp;
+ }
- @Override
- public void wield() {
- getImp().wieldImp();
- }
+ @Override
+ public void wield() {
+ getImp().wieldImp();
+ }
- @Override
- public void swing() {
- getImp().swingImp();
- }
+ @Override
+ public void swing() {
+ getImp().swingImp();
+ }
- @Override
- public void unwield() {
- getImp().unwieldImp();
- }
+ @Override
+ public void unwield() {
+ getImp().unwieldImp();
+ }
- public void fly() {
- getImp().flyImp();
- }
+ public void fly() {
+ getImp().flyImp();
+ }
}
diff --git a/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeaponImpl.java b/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeaponImpl.java
index 8b7a10f2f..022c06565 100644
--- a/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeaponImpl.java
+++ b/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeaponImpl.java
@@ -7,6 +7,6 @@ package com.iluwatar.bridge;
*/
public abstract class FlyingMagicWeaponImpl extends MagicWeaponImpl {
- public abstract void flyImp();
+ public abstract void flyImp();
}
diff --git a/bridge/src/main/java/com/iluwatar/bridge/MagicWeapon.java b/bridge/src/main/java/com/iluwatar/bridge/MagicWeapon.java
index b2b82839c..5e17d2b40 100644
--- a/bridge/src/main/java/com/iluwatar/bridge/MagicWeapon.java
+++ b/bridge/src/main/java/com/iluwatar/bridge/MagicWeapon.java
@@ -7,20 +7,19 @@ package com.iluwatar.bridge;
*/
public abstract class MagicWeapon {
- protected MagicWeaponImpl imp;
+ protected MagicWeaponImpl imp;
- public MagicWeapon(MagicWeaponImpl imp) {
- this.imp = imp;
- }
+ public MagicWeapon(MagicWeaponImpl 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 MagicWeaponImpl getImp() {
- return imp;
- }
+ public abstract void unwield();
+ public MagicWeaponImpl getImp() {
+ return imp;
+ }
}
diff --git a/bridge/src/main/java/com/iluwatar/bridge/MagicWeaponImpl.java b/bridge/src/main/java/com/iluwatar/bridge/MagicWeaponImpl.java
index bd2a3b8d7..bc672335e 100644
--- a/bridge/src/main/java/com/iluwatar/bridge/MagicWeaponImpl.java
+++ b/bridge/src/main/java/com/iluwatar/bridge/MagicWeaponImpl.java
@@ -7,10 +7,10 @@ package com.iluwatar.bridge;
*/
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();
}
diff --git a/bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java b/bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java
index 887173add..13641c335 100644
--- a/bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java
+++ b/bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java
@@ -7,25 +7,23 @@ package com.iluwatar.bridge;
*/
public class Mjollnir extends FlyingMagicWeaponImpl {
- @Override
- public void wieldImp() {
- System.out.println("wielding Mjollnir");
- }
+ @Override
+ public void wieldImp() {
+ System.out.println("wielding Mjollnir");
+ }
- @Override
- public void swingImp() {
- System.out.println("swinging Mjollnir");
- }
+ @Override
+ public void swingImp() {
+ System.out.println("swinging Mjollnir");
+ }
- @Override
- public void unwieldImp() {
- 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 unwieldImp() {
+ 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");
+ }
}
diff --git a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeapon.java b/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeapon.java
index 3310b6488..991719c31 100644
--- a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeapon.java
+++ b/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeapon.java
@@ -7,32 +7,32 @@ package com.iluwatar.bridge;
*/
public class SoulEatingMagicWeapon extends MagicWeapon {
- public SoulEatingMagicWeapon(SoulEatingMagicWeaponImpl imp) {
- super(imp);
- }
+ public SoulEatingMagicWeapon(SoulEatingMagicWeaponImpl imp) {
+ super(imp);
+ }
- @Override
- public SoulEatingMagicWeaponImpl getImp() {
- return (SoulEatingMagicWeaponImpl) imp;
- }
+ @Override
+ public SoulEatingMagicWeaponImpl getImp() {
+ return (SoulEatingMagicWeaponImpl) imp;
+ }
- @Override
- public void wield() {
- getImp().wieldImp();
- }
+ @Override
+ public void wield() {
+ getImp().wieldImp();
+ }
- @Override
- public void swing() {
- getImp().swingImp();
- }
+ @Override
+ public void swing() {
+ getImp().swingImp();
+ }
- @Override
- public void unwield() {
- getImp().unwieldImp();
- }
+ @Override
+ public void unwield() {
+ getImp().unwieldImp();
+ }
- public void eatSoul() {
- getImp().eatSoulImp();
- }
+ public void eatSoul() {
+ getImp().eatSoulImp();
+ }
}
diff --git a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeaponImpl.java b/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeaponImpl.java
index 9ec112031..ec2c3a941 100644
--- a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeaponImpl.java
+++ b/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeaponImpl.java
@@ -7,6 +7,6 @@ package com.iluwatar.bridge;
*/
public abstract class SoulEatingMagicWeaponImpl extends MagicWeaponImpl {
- public abstract void eatSoulImp();
+ public abstract void eatSoulImp();
}
diff --git a/bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java b/bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java
index 589156fe3..ebbe0c23f 100644
--- a/bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java
+++ b/bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java
@@ -7,24 +7,23 @@ package com.iluwatar.bridge;
*/
public class Stormbringer extends SoulEatingMagicWeaponImpl {
- @Override
- public void wieldImp() {
- System.out.println("wielding Stormbringer");
- }
+ @Override
+ public void wieldImp() {
+ System.out.println("wielding Stormbringer");
+ }
- @Override
- public void swingImp() {
- System.out.println("swinging Stormbringer");
- }
+ @Override
+ public void swingImp() {
+ System.out.println("swinging Stormbringer");
+ }
- @Override
- public void unwieldImp() {
- System.out.println("unwielding Stormbringer");
- }
-
- @Override
- public void eatSoulImp() {
- System.out.println("Stormbringer devours the enemy's soul");
- }
+ @Override
+ public void unwieldImp() {
+ System.out.println("unwielding Stormbringer");
+ }
+ @Override
+ public void eatSoulImp() {
+ System.out.println("Stormbringer devours the enemy's soul");
+ }
}
diff --git a/bridge/src/test/java/com/iluwatar/bridge/AppTest.java b/bridge/src/test/java/com/iluwatar/bridge/AppTest.java
index b53111c8e..99faad43e 100644
--- a/bridge/src/test/java/com/iluwatar/bridge/AppTest.java
+++ b/bridge/src/test/java/com/iluwatar/bridge/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.bridge.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/builder/src/main/java/com/iluwatar/builder/App.java b/builder/src/main/java/com/iluwatar/builder/App.java
index b6131c3ab..b5c8fd7a9 100644
--- a/builder/src/main/java/com/iluwatar/builder/App.java
+++ b/builder/src/main/java/com/iluwatar/builder/App.java
@@ -1,55 +1,55 @@
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 anti-pattern. The telescoping constructor anti-pattern occurs when the
- * increase of object 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.
+ * The intention of the Builder pattern is to find a solution to the telescoping constructor
+ * anti-pattern. The telescoping constructor anti-pattern occurs when the increase of object
+ * 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.
*
- * The Builder pattern has another benefit. It can be used for objects that contain
- * flat data (html code, SQL query, X.509 certificate...), that is to say, data that
- * can't be easily edited. This type of data cannot be edited step by step and must
- * be edited at once. The best way to construct such an object is to use a builder
- * class.
+ * The Builder pattern has another benefit. It can be used for objects that contain flat data (html
+ * code, SQL query, X.509 certificate...), that is to say, data that can't be easily edited. This
+ * type of data cannot be edited step by step and must be edited at once. The best way to construct
+ * such an object is to use a builder class.
*
- * In this example we have the Builder pattern variation as described by Joshua Bloch in
- * Effective Java 2nd Edition.
+ * In this example we have the Builder pattern variation as described by Joshua Bloch in Effective
+ * Java 2nd Edition.
*
- * 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.
+ * 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 {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
- Hero mage = new HeroBuilder(Profession.MAGE, "Riobard")
- .withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER)
- .build();
- System.out.println(mage);
+ Hero mage =
+ new HeroBuilder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK)
+ .withWeapon(Weapon.DAGGER).build();
+ System.out.println(mage);
- Hero warrior = new HeroBuilder(Profession.WARRIOR, "Amberjill")
- .withHairColor(HairColor.BLOND)
- .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL)
- .withWeapon(Weapon.SWORD).build();
- System.out.println(warrior);
+ Hero warrior =
+ new HeroBuilder(Profession.WARRIOR, "Amberjill").withHairColor(HairColor.BLOND)
+ .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD)
+ .build();
+ System.out.println(warrior);
- Hero thief = new HeroBuilder(Profession.THIEF, "Desmond")
- .withHairType(HairType.BALD).withWeapon(Weapon.BOW).build();
- System.out.println(thief);
+ Hero thief =
+ new HeroBuilder(Profession.THIEF, "Desmond").withHairType(HairType.BALD)
+ .withWeapon(Weapon.BOW).build();
+ System.out.println(thief);
- }
+ }
}
diff --git a/builder/src/main/java/com/iluwatar/builder/Armor.java b/builder/src/main/java/com/iluwatar/builder/Armor.java
index 95fcba43b..6b67b8f94 100644
--- a/builder/src/main/java/com/iluwatar/builder/Armor.java
+++ b/builder/src/main/java/com/iluwatar/builder/Armor.java
@@ -7,16 +7,16 @@ package com.iluwatar.builder;
*/
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) {
- this.title = title;
- }
+ Armor(String title) {
+ this.title = title;
+ }
- @Override
- public String toString() {
- return title;
- }
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/builder/src/main/java/com/iluwatar/builder/HairColor.java b/builder/src/main/java/com/iluwatar/builder/HairColor.java
index dd8ec2ecc..b99b3db63 100644
--- a/builder/src/main/java/com/iluwatar/builder/HairColor.java
+++ b/builder/src/main/java/com/iluwatar/builder/HairColor.java
@@ -7,11 +7,11 @@ package com.iluwatar.builder;
*/
public enum HairColor {
- WHITE, BLOND, RED, BROWN, BLACK;
+ WHITE, BLOND, RED, BROWN, BLACK;
- @Override
- public String toString() {
- return name().toLowerCase();
- }
+ @Override
+ public String toString() {
+ return name().toLowerCase();
+ }
}
diff --git a/builder/src/main/java/com/iluwatar/builder/HairType.java b/builder/src/main/java/com/iluwatar/builder/HairType.java
index ea49c0470..48eeac950 100644
--- a/builder/src/main/java/com/iluwatar/builder/HairType.java
+++ b/builder/src/main/java/com/iluwatar/builder/HairType.java
@@ -7,16 +7,17 @@ package com.iluwatar.builder;
*/
public enum HairType {
- BALD("bald"), SHORT("short"), CURLY("curly"), LONG_STRAIGHT("long straight"), LONG_CURLY("long curly");
+ BALD("bald"), SHORT("short"), CURLY("curly"), LONG_STRAIGHT("long straight"), LONG_CURLY(
+ "long curly");
- private String title;
+ private String title;
- HairType(String title) {
- this.title = title;
- }
+ HairType(String title) {
+ this.title = title;
+ }
- @Override
- public String toString() {
- return title;
- }
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/builder/src/main/java/com/iluwatar/builder/Hero.java b/builder/src/main/java/com/iluwatar/builder/Hero.java
index 05304bf09..54be11ea3 100644
--- a/builder/src/main/java/com/iluwatar/builder/Hero.java
+++ b/builder/src/main/java/com/iluwatar/builder/Hero.java
@@ -7,123 +7,122 @@ package com.iluwatar.builder;
*/
public class Hero {
- private final Profession profession;
- private final String name;
- private final HairType hairType;
- private final HairColor hairColor;
- private final Armor armor;
- private final Weapon weapon;
+ private final Profession profession;
+ private final String name;
+ private final HairType hairType;
+ private final HairColor hairColor;
+ private final Armor armor;
+ private final Weapon weapon;
- public Profession getProfession() {
- return profession;
- }
+ public Profession getProfession() {
+ return profession;
+ }
- public String getName() {
- return name;
- }
+ public String getName() {
+ return name;
+ }
- public HairType getHairType() {
- return hairType;
- }
+ public HairType getHairType() {
+ return hairType;
+ }
- public HairColor getHairColor() {
- return hairColor;
- }
+ public HairColor getHairColor() {
+ return hairColor;
+ }
- public Armor getArmor() {
- return armor;
- }
+ public Armor getArmor() {
+ return armor;
+ }
- public Weapon getWeapon() {
- return weapon;
- }
+ public Weapon getWeapon() {
+ return weapon;
+ }
- @Override
- public String toString() {
+ @Override
+ public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("This is a ");
- sb.append(profession);
- sb.append(" named ");
- sb.append(name);
- if (hairColor != null || hairType != null) {
- sb.append(" with ");
- if (hairColor != null) {
- sb.append(hairColor);
- sb.append(" ");
- }
- if (hairType != null) {
- sb.append(hairType);
- sb.append(" ");
- }
- sb.append(hairType != HairType.BALD ? "hair" : "head");
- }
- if (armor != null) {
- sb.append(" wearing ");
- sb.append(armor);
- }
- if (weapon != null) {
- sb.append(" and wielding a ");
- sb.append(weapon);
- }
- sb.append(".");
- return sb.toString();
- }
+ StringBuilder sb = new StringBuilder();
+ sb.append("This is a ");
+ sb.append(profession);
+ sb.append(" named ");
+ sb.append(name);
+ if (hairColor != null || hairType != null) {
+ sb.append(" with ");
+ if (hairColor != null) {
+ sb.append(hairColor);
+ sb.append(" ");
+ }
+ if (hairType != null) {
+ sb.append(hairType);
+ sb.append(" ");
+ }
+ sb.append(hairType != HairType.BALD ? "hair" : "head");
+ }
+ if (armor != null) {
+ sb.append(" wearing ");
+ sb.append(armor);
+ }
+ if (weapon != null) {
+ sb.append(" and wielding a ");
+ sb.append(weapon);
+ }
+ sb.append(".");
+ return sb.toString();
+ }
- private Hero(HeroBuilder builder) {
- this.profession = builder.profession;
- this.name = builder.name;
- this.hairColor = builder.hairColor;
- this.hairType = builder.hairType;
- this.weapon = builder.weapon;
- this.armor = builder.armor;
- }
+ private Hero(HeroBuilder builder) {
+ this.profession = builder.profession;
+ this.name = builder.name;
+ this.hairColor = builder.hairColor;
+ this.hairType = builder.hairType;
+ this.weapon = builder.weapon;
+ this.armor = builder.armor;
+ }
- /**
- *
- * The builder class.
- *
- */
- public static class HeroBuilder {
+ /**
+ *
+ * The builder class.
+ *
+ */
+ public static class HeroBuilder {
- private final Profession profession;
- private final String name;
- private HairType hairType;
- private HairColor hairColor;
- private Armor armor;
- private Weapon weapon;
+ private final Profession profession;
+ private final String name;
+ private HairType hairType;
+ private HairColor hairColor;
+ private Armor armor;
+ private Weapon weapon;
- public HeroBuilder(Profession profession, String name) {
- if (profession == null || name == null) {
- throw new IllegalArgumentException(
- "profession and name can not be null");
- }
- this.profession = profession;
- this.name = name;
- }
+ public HeroBuilder(Profession profession, String name) {
+ if (profession == null || name == null) {
+ throw new IllegalArgumentException("profession and name can not be null");
+ }
+ this.profession = profession;
+ this.name = name;
+ }
- public HeroBuilder withHairType(HairType hairType) {
- this.hairType = hairType;
- return this;
- }
+ public HeroBuilder withHairType(HairType hairType) {
+ this.hairType = hairType;
+ return this;
+ }
- public HeroBuilder withHairColor(HairColor hairColor) {
- this.hairColor = hairColor;
- return this;
- }
+ public HeroBuilder withHairColor(HairColor hairColor) {
+ this.hairColor = hairColor;
+ return this;
+ }
- public HeroBuilder withArmor(Armor armor) {
- this.armor = armor;
- return this;
- }
+ public HeroBuilder withArmor(Armor armor) {
+ this.armor = armor;
+ return this;
+ }
- public HeroBuilder withWeapon(Weapon weapon) {
- this.weapon = weapon;
- return this;
- }
+ public HeroBuilder withWeapon(Weapon weapon) {
+ this.weapon = weapon;
+ return this;
+ }
- public Hero build() {
- return new Hero(this);
- }
- }
+ public Hero build() {
+ return new Hero(this);
+ }
+ }
}
diff --git a/builder/src/main/java/com/iluwatar/builder/Profession.java b/builder/src/main/java/com/iluwatar/builder/Profession.java
index c9a7cc4e9..a157366b4 100644
--- a/builder/src/main/java/com/iluwatar/builder/Profession.java
+++ b/builder/src/main/java/com/iluwatar/builder/Profession.java
@@ -7,11 +7,10 @@ package com.iluwatar.builder;
*/
public enum Profession {
- WARRIOR, THIEF, MAGE, PRIEST;
-
- @Override
- public String toString() {
- return name().toLowerCase();
- }
+ WARRIOR, THIEF, MAGE, PRIEST;
+ @Override
+ public String toString() {
+ return name().toLowerCase();
+ }
}
diff --git a/builder/src/main/java/com/iluwatar/builder/Weapon.java b/builder/src/main/java/com/iluwatar/builder/Weapon.java
index af71c596d..08f55c65c 100644
--- a/builder/src/main/java/com/iluwatar/builder/Weapon.java
+++ b/builder/src/main/java/com/iluwatar/builder/Weapon.java
@@ -7,11 +7,10 @@ package com.iluwatar.builder;
*/
public enum Weapon {
- DAGGER, SWORD, AXE, WARHAMMER, BOW;
-
- @Override
- public String toString() {
- return name().toLowerCase();
- }
+ DAGGER, SWORD, AXE, WARHAMMER, BOW;
+ @Override
+ public String toString() {
+ return name().toLowerCase();
+ }
}
diff --git a/builder/src/test/java/com/iluwatar/builder/AppTest.java b/builder/src/test/java/com/iluwatar/builder/AppTest.java
index acae1ca70..857f49dc9 100644
--- a/builder/src/test/java/com/iluwatar/builder/AppTest.java
+++ b/builder/src/test/java/com/iluwatar/builder/AppTest.java
@@ -2,7 +2,7 @@ package com.iluwatar.builder;
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 {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java
index eea7608eb..c900f7366 100644
--- a/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java
+++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java
@@ -2,34 +2,36 @@ package com.iluwatar.business.delegate;
/**
*
- * The Business Delegate pattern adds an abstraction layer between the presentation and business tiers.
- * By using the pattern we gain loose coupling between the tiers. The Business Delegate encapsulates
- * knowledge about how to locate, connect to, and interact with the business objects that make up
- * the application.
+ * The Business Delegate pattern adds an abstraction layer between the presentation and business
+ * tiers. 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.
*
- * 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.
+ * 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.
*
- * 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.
+ * 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 {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
-
- BusinessDelegate businessDelegate = new BusinessDelegate();
- businessDelegate.setServiceType(ServiceType.EJB);
- Client client = new Client(businessDelegate);
- client.doTask();
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
- businessDelegate.setServiceType(ServiceType.JMS);
- client.doTask();
- }
+ BusinessDelegate businessDelegate = new BusinessDelegate();
+ businessDelegate.setServiceType(ServiceType.EJB);
+
+ Client client = new Client(businessDelegate);
+ client.doTask();
+
+ businessDelegate.setServiceType(ServiceType.JMS);
+ client.doTask();
+ }
}
diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java
index cf0809b97..b8a70aa0e 100644
--- a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java
+++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java
@@ -6,17 +6,17 @@ package com.iluwatar.business.delegate;
*
*/
public class BusinessDelegate {
-
- private BusinessLookup lookupService = new BusinessLookup();
- private BusinessService businessService;
- private ServiceType serviceType;
- public void setServiceType(ServiceType serviceType) {
- this.serviceType = serviceType;
- }
+ private BusinessLookup lookupService = new BusinessLookup();
+ private BusinessService businessService;
+ private ServiceType serviceType;
- public void doTask() {
- businessService = lookupService.getBusinessService(serviceType);
- businessService.doProcessing();
- }
+ public void setServiceType(ServiceType serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public void doTask() {
+ businessService = lookupService.getBusinessService(serviceType);
+ businessService.doProcessing();
+ }
}
diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java
index 6a5f2d504..7cea16580 100644
--- a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java
+++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java
@@ -7,11 +7,11 @@ package com.iluwatar.business.delegate;
*/
public class BusinessLookup {
- public BusinessService getBusinessService(ServiceType serviceType) {
- if (serviceType.equals(ServiceType.EJB)) {
- return new EjbService();
- } else {
- return new JmsService();
- }
- }
+ public BusinessService getBusinessService(ServiceType serviceType) {
+ if (serviceType.equals(ServiceType.EJB)) {
+ return new EjbService();
+ } else {
+ return new JmsService();
+ }
+ }
}
diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessService.java
index 7e39745d5..dfeaf883a 100644
--- a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessService.java
+++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessService.java
@@ -7,5 +7,5 @@ package com.iluwatar.business.delegate;
*/
public interface BusinessService {
- void doProcessing();
+ void doProcessing();
}
diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/Client.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/Client.java
index 2dc0cc662..eab295cf2 100644
--- a/business-delegate/src/main/java/com/iluwatar/business/delegate/Client.java
+++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/Client.java
@@ -7,13 +7,13 @@ package com.iluwatar.business.delegate;
*/
public class Client {
- private BusinessDelegate businessDelegate;
+ private BusinessDelegate businessDelegate;
- public Client(BusinessDelegate businessDelegate) {
- this.businessDelegate = businessDelegate;
- }
+ public Client(BusinessDelegate businessDelegate) {
+ this.businessDelegate = businessDelegate;
+ }
- public void doTask() {
- businessDelegate.doTask();
- }
+ public void doTask() {
+ businessDelegate.doTask();
+ }
}
diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java
index bd03db45d..f387449e2 100644
--- a/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java
+++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java
@@ -7,8 +7,8 @@ package com.iluwatar.business.delegate;
*/
public class EjbService implements BusinessService {
- @Override
- public void doProcessing() {
- System.out.println("EjbService is now processing");
- }
+ @Override
+ public void doProcessing() {
+ System.out.println("EjbService is now processing");
+ }
}
diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java
index 37425755a..fd74cf3c2 100644
--- a/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java
+++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java
@@ -7,8 +7,8 @@ package com.iluwatar.business.delegate;
*/
public class JmsService implements BusinessService {
- @Override
- public void doProcessing() {
- System.out.println("JmsService is now processing");
- }
+ @Override
+ public void doProcessing() {
+ System.out.println("JmsService is now processing");
+ }
}
diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/ServiceType.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/ServiceType.java
index e26d71ae6..ac42d3b6c 100644
--- a/business-delegate/src/main/java/com/iluwatar/business/delegate/ServiceType.java
+++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/ServiceType.java
@@ -6,6 +6,6 @@ package com.iluwatar.business.delegate;
*
*/
public enum ServiceType {
-
- EJB, JMS;
+
+ EJB, JMS;
}
diff --git a/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java b/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java
index 7ce63c2b4..5ff7e6784 100644
--- a/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java
+++ b/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java
@@ -10,10 +10,10 @@ import com.iluwatar.business.delegate.App;
*
*/
public class AppTest {
-
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/callback/src/main/java/com/iluwatar/callback/App.java b/callback/src/main/java/com/iluwatar/callback/App.java
index 513a32415..81cb16f73 100644
--- a/callback/src/main/java/com/iluwatar/callback/App.java
+++ b/callback/src/main/java/com/iluwatar/callback/App.java
@@ -2,20 +2,21 @@ package com.iluwatar.callback;
/**
*
- * Callback pattern is more native for functional languages where functions are treated as first-class citizens.
- * Prior to Java 8 callbacks can be simulated using simple (alike command) interfaces.
+ * Callback pattern is more native for functional languages where functions are treated as
+ * first-class citizens. Prior to Java 8 callbacks can be simulated using simple (alike command)
+ * interfaces.
*
*/
public class App {
- public static void main(String[] args) {
- Task task = new SimpleTask();
- Callback callback = new Callback() {
- @Override
- public void call() {
- System.out.println("I'm done now.");
- }
- };
- task.executeWith(callback);
- }
+ public static void main(String[] args) {
+ Task task = new SimpleTask();
+ Callback callback = new Callback() {
+ @Override
+ public void call() {
+ System.out.println("I'm done now.");
+ }
+ };
+ task.executeWith(callback);
+ }
}
diff --git a/callback/src/main/java/com/iluwatar/callback/Callback.java b/callback/src/main/java/com/iluwatar/callback/Callback.java
index 81a421c0d..08939298b 100644
--- a/callback/src/main/java/com/iluwatar/callback/Callback.java
+++ b/callback/src/main/java/com/iluwatar/callback/Callback.java
@@ -7,5 +7,5 @@ package com.iluwatar.callback;
*/
public interface Callback {
- public void call();
+ public void call();
}
diff --git a/callback/src/main/java/com/iluwatar/callback/SimpleTask.java b/callback/src/main/java/com/iluwatar/callback/SimpleTask.java
index 70b844ce3..a651ed7b6 100644
--- a/callback/src/main/java/com/iluwatar/callback/SimpleTask.java
+++ b/callback/src/main/java/com/iluwatar/callback/SimpleTask.java
@@ -7,9 +7,8 @@ package com.iluwatar.callback;
*/
public class SimpleTask extends Task {
- @Override
- public void execute() {
- System.out.println("Perform some important activity and after call the callback method.");
- }
-
+ @Override
+ public void execute() {
+ System.out.println("Perform some important activity and after call the callback method.");
+ }
}
diff --git a/callback/src/main/java/com/iluwatar/callback/Task.java b/callback/src/main/java/com/iluwatar/callback/Task.java
index db4b66dc5..d3be6c7a0 100644
--- a/callback/src/main/java/com/iluwatar/callback/Task.java
+++ b/callback/src/main/java/com/iluwatar/callback/Task.java
@@ -7,12 +7,12 @@ package com.iluwatar.callback;
*/
public abstract class Task {
- public final void executeWith(Callback callback) {
- execute();
- if (callback != null) {
- callback.call();
- }
- }
+ public final void executeWith(Callback callback) {
+ execute();
+ if (callback != null) {
+ callback.call();
+ }
+ }
- public abstract void execute();
+ public abstract void execute();
}
diff --git a/callback/src/test/java/com/iluwatar/callback/AppTest.java b/callback/src/test/java/com/iluwatar/callback/AppTest.java
index 0f7a6f45e..67046a175 100644
--- a/callback/src/test/java/com/iluwatar/callback/AppTest.java
+++ b/callback/src/test/java/com/iluwatar/callback/AppTest.java
@@ -5,35 +5,35 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
- * 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.
+ * 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.
*
* Could be done with mock objects as well where the call method call is verified.
*/
public class AppTest {
- private Integer callingCount = 0;
+ private Integer callingCount = 0;
- @Test
- public void test() {
- Callback callback = new Callback() {
- @Override
- public void call() {
- callingCount++;
- }
- };
+ @Test
+ public void test() {
+ Callback callback = new Callback() {
+ @Override
+ public void call() {
+ callingCount++;
+ }
+ };
- Task task = new SimpleTask();
+ Task task = new SimpleTask();
- assertEquals("Initial calling count of 0", new Integer(0), callingCount);
+ assertEquals("Initial calling count of 0", new Integer(0), callingCount);
- task.executeWith(callback);
+ task.executeWith(callback);
- assertEquals("Callback called once", new Integer(1), callingCount);
+ assertEquals("Callback called once", new Integer(1), callingCount);
- task.executeWith(callback);
+ task.executeWith(callback);
- assertEquals("Callback called twice", new Integer(2), callingCount);
+ assertEquals("Callback called twice", new Integer(2), callingCount);
- }
+ }
}
diff --git a/chain/src/main/java/com/iluwatar/chain/App.java b/chain/src/main/java/com/iluwatar/chain/App.java
index 4d3ca69db..ae8c74143 100644
--- a/chain/src/main/java/com/iluwatar/chain/App.java
+++ b/chain/src/main/java/com/iluwatar/chain/App.java
@@ -2,31 +2,30 @@ package com.iluwatar.chain;
/**
*
- * The Chain of Responsibility pattern is a design pattern consisting of command
- * objects and a series of processing objects. Each processing object contains
- * logic that defines the types of command objects that it can handle; the rest are
- * passed to the next processing object in the chain. A mechanism also exists for
- * adding new processing objects to the end of this chain.
+ * The Chain of Responsibility pattern is a design pattern consisting of command objects and a
+ * series of processing objects. Each processing object contains logic that defines the types of
+ * command objects that it can handle; the rest are passed to the next processing object in the
+ * chain. A mechanism also exists for adding new processing objects to the end of this chain.
*
- * 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.
+ * 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 {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
- OrcKing king = new OrcKing();
- king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle"));
- king.makeRequest(new Request(RequestType.TORTURE_PRISONER,
- "torture prisoner"));
- king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax"));
+ OrcKing king = new OrcKing();
+ king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle"));
+ king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner"));
+ king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax"));
- }
+ }
}
diff --git a/chain/src/main/java/com/iluwatar/chain/OrcCommander.java b/chain/src/main/java/com/iluwatar/chain/OrcCommander.java
index fb5134e01..73de1b8b2 100644
--- a/chain/src/main/java/com/iluwatar/chain/OrcCommander.java
+++ b/chain/src/main/java/com/iluwatar/chain/OrcCommander.java
@@ -7,21 +7,21 @@ package com.iluwatar.chain;
*/
public class OrcCommander extends RequestHandler {
- public OrcCommander(RequestHandler handler) {
- super(handler);
- }
+ public OrcCommander(RequestHandler handler) {
+ super(handler);
+ }
- @Override
- public void handleRequest(Request req) {
- if (req.getRequestType().equals(RequestType.DEFEND_CASTLE)) {
- printHandling(req);
- } else {
- super.handleRequest(req);
- }
- }
+ @Override
+ public void handleRequest(Request req) {
+ if (req.getRequestType().equals(RequestType.DEFEND_CASTLE)) {
+ printHandling(req);
+ } else {
+ super.handleRequest(req);
+ }
+ }
- @Override
- public String toString() {
- return "Orc commander";
- }
+ @Override
+ public String toString() {
+ return "Orc commander";
+ }
}
diff --git a/chain/src/main/java/com/iluwatar/chain/OrcKing.java b/chain/src/main/java/com/iluwatar/chain/OrcKing.java
index b39959935..640b190b2 100644
--- a/chain/src/main/java/com/iluwatar/chain/OrcKing.java
+++ b/chain/src/main/java/com/iluwatar/chain/OrcKing.java
@@ -7,18 +7,18 @@ package com.iluwatar.chain;
*/
public class OrcKing {
- RequestHandler chain;
+ RequestHandler chain;
- public OrcKing() {
- buildChain();
- }
+ public OrcKing() {
+ buildChain();
+ }
- private void buildChain() {
- chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null)));
- }
+ private void buildChain() {
+ chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null)));
+ }
- public void makeRequest(Request req) {
- chain.handleRequest(req);
- }
+ public void makeRequest(Request req) {
+ chain.handleRequest(req);
+ }
}
diff --git a/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java b/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java
index 131cb1101..68df3ec6f 100644
--- a/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java
+++ b/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java
@@ -7,22 +7,22 @@ package com.iluwatar.chain;
*/
public class OrcOfficer extends RequestHandler {
- public OrcOfficer(RequestHandler handler) {
- super(handler);
- }
+ public OrcOfficer(RequestHandler handler) {
+ super(handler);
+ }
- @Override
- public void handleRequest(Request req) {
- if (req.getRequestType().equals(RequestType.TORTURE_PRISONER)) {
- printHandling(req);
- } else {
- super.handleRequest(req);
- }
- }
+ @Override
+ public void handleRequest(Request req) {
+ if (req.getRequestType().equals(RequestType.TORTURE_PRISONER)) {
+ printHandling(req);
+ } else {
+ super.handleRequest(req);
+ }
+ }
- @Override
- public String toString() {
- return "Orc officer";
- }
+ @Override
+ public String toString() {
+ return "Orc officer";
+ }
}
diff --git a/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java b/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java
index a681dfb77..d96f51702 100644
--- a/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java
+++ b/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java
@@ -7,21 +7,21 @@ package com.iluwatar.chain;
*/
public class OrcSoldier extends RequestHandler {
- public OrcSoldier(RequestHandler handler) {
- super(handler);
- }
+ public OrcSoldier(RequestHandler handler) {
+ super(handler);
+ }
- @Override
- public void handleRequest(Request req) {
- if (req.getRequestType().equals(RequestType.COLLECT_TAX)) {
- printHandling(req);
- } else {
- super.handleRequest(req);
- }
- }
+ @Override
+ public void handleRequest(Request req) {
+ if (req.getRequestType().equals(RequestType.COLLECT_TAX)) {
+ printHandling(req);
+ } else {
+ super.handleRequest(req);
+ }
+ }
- @Override
- public String toString() {
- return "Orc soldier";
- }
+ @Override
+ public String toString() {
+ return "Orc soldier";
+ }
}
diff --git a/chain/src/main/java/com/iluwatar/chain/Request.java b/chain/src/main/java/com/iluwatar/chain/Request.java
index 558ee65d1..0c62cfd43 100644
--- a/chain/src/main/java/com/iluwatar/chain/Request.java
+++ b/chain/src/main/java/com/iluwatar/chain/Request.java
@@ -7,32 +7,32 @@ package com.iluwatar.chain;
*/
public class Request {
- private String requestDescription;
- private RequestType requestType;
+ private String requestDescription;
+ private RequestType requestType;
- public Request(RequestType requestType, String requestDescription) {
- this.setRequestType(requestType);
- this.setRequestDescription(requestDescription);
- }
+ public Request(RequestType requestType, String requestDescription) {
+ this.setRequestType(requestType);
+ this.setRequestDescription(requestDescription);
+ }
- public String getRequestDescription() {
- return requestDescription;
- }
+ public String getRequestDescription() {
+ return requestDescription;
+ }
- public void setRequestDescription(String requestDescription) {
- this.requestDescription = requestDescription;
- }
+ public void setRequestDescription(String requestDescription) {
+ this.requestDescription = requestDescription;
+ }
- public RequestType getRequestType() {
- return requestType;
- }
+ public RequestType getRequestType() {
+ return requestType;
+ }
- public void setRequestType(RequestType requestType) {
- this.requestType = requestType;
- }
+ public void setRequestType(RequestType requestType) {
+ this.requestType = requestType;
+ }
- @Override
- public String toString() {
- return getRequestDescription();
- }
+ @Override
+ public String toString() {
+ return getRequestDescription();
+ }
}
diff --git a/chain/src/main/java/com/iluwatar/chain/RequestHandler.java b/chain/src/main/java/com/iluwatar/chain/RequestHandler.java
index 5570c20ce..fd58b9ea8 100644
--- a/chain/src/main/java/com/iluwatar/chain/RequestHandler.java
+++ b/chain/src/main/java/com/iluwatar/chain/RequestHandler.java
@@ -7,22 +7,22 @@ package com.iluwatar.chain;
*/
public abstract class RequestHandler {
- private RequestHandler next;
+ private RequestHandler next;
- public RequestHandler(RequestHandler next) {
- this.next = next;
- }
+ public RequestHandler(RequestHandler next) {
+ this.next = next;
+ }
- public void handleRequest(Request req) {
- if (next != null) {
- next.handleRequest(req);
- }
- }
+ public void handleRequest(Request req) {
+ if (next != null) {
+ next.handleRequest(req);
+ }
+ }
- protected void printHandling(Request req) {
- System.out.println(this + " handling request \"" + req + "\"");
- }
+ protected void printHandling(Request req) {
+ System.out.println(this + " handling request \"" + req + "\"");
+ }
- @Override
- public abstract String toString();
+ @Override
+ public abstract String toString();
}
diff --git a/chain/src/main/java/com/iluwatar/chain/RequestType.java b/chain/src/main/java/com/iluwatar/chain/RequestType.java
index 9ad975d2f..443d6dced 100644
--- a/chain/src/main/java/com/iluwatar/chain/RequestType.java
+++ b/chain/src/main/java/com/iluwatar/chain/RequestType.java
@@ -7,6 +7,6 @@ package com.iluwatar.chain;
*/
public enum RequestType {
- DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX
+ DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX
}
diff --git a/chain/src/test/java/com/iluwatar/chain/AppTest.java b/chain/src/test/java/com/iluwatar/chain/AppTest.java
index aa52e60e2..bd28b007a 100644
--- a/chain/src/test/java/com/iluwatar/chain/AppTest.java
+++ b/chain/src/test/java/com/iluwatar/chain/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.chain.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/command/src/main/java/com/iluwatar/command/App.java b/command/src/main/java/com/iluwatar/command/App.java
index b421b683b..423ce6075 100644
--- a/command/src/main/java/com/iluwatar/command/App.java
+++ b/command/src/main/java/com/iluwatar/command/App.java
@@ -2,52 +2,54 @@ package com.iluwatar.command;
/**
*
- * The Command pattern is a behavioral design pattern in which an object is used to encapsulate all information
- * needed to perform an action or trigger an event at a later time. This information includes the method name,
- * the object that owns the method and values for the method parameters.
+ * The Command pattern is a behavioral design pattern in which an object is used to encapsulate all
+ * information needed to perform an action or trigger an event at a later time. This information
+ * includes the method name, the object that owns the method and values for the method parameters.
*
- * Four terms always associated with the command pattern are command, receiver, invoker and client. A command
- * object (spell) knows about the receiver (target) and invokes a method of the receiver. Values for parameters of
- * the receiver method are stored in the command. The receiver then does the work. An invoker object (wizard)
- * knows how to execute a command, and optionally does bookkeeping about the command execution. The invoker
- * does not know anything about a concrete command, it knows only about command interface. Both an invoker object
- * and several command objects are held by a client object (app). The client decides which commands to execute at
- * which points. To execute a command, it passes the command object to the invoker object.
+ * Four terms always associated with the command pattern are command, receiver, invoker and client.
+ * A command object (spell) knows about the receiver (target) and invokes a method of the receiver.
+ * Values for parameters of the receiver method are stored in the command. The receiver then does
+ * the work. An invoker object (wizard) knows how to execute a command, and optionally does
+ * bookkeeping about the command execution. The invoker does not know anything about a concrete
+ * command, it knows only about command interface. Both an invoker object and several command
+ * objects are held by a client object (app). The client decides which commands to execute at which
+ * points. To execute a command, it passes the command object to the invoker object.
*
- * In other words, in this example the wizard casts spells on the goblin. The wizard keeps track of the previous
- * spells cast, so it is easy to undo them. In addition, the wizard keeps track of the spells undone, so they
- * can be redone.
+ * In other words, in this example the wizard casts spells on the goblin. The wizard keeps track of
+ * the previous spells cast, so it is easy to undo them. In addition, the wizard keeps track of the
+ * spells undone, so they can be redone.
*
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- Wizard wizard = new Wizard();
- Goblin goblin = new Goblin();
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ Wizard wizard = new Wizard();
+ Goblin goblin = new Goblin();
- goblin.printStatus();
+ goblin.printStatus();
- wizard.castSpell(new ShrinkSpell(), goblin);
- goblin.printStatus();
+ wizard.castSpell(new ShrinkSpell(), goblin);
+ goblin.printStatus();
- wizard.castSpell(new InvisibilitySpell(), goblin);
- goblin.printStatus();
+ wizard.castSpell(new InvisibilitySpell(), goblin);
+ goblin.printStatus();
- wizard.undoLastSpell();
- goblin.printStatus();
+ wizard.undoLastSpell();
+ goblin.printStatus();
- wizard.undoLastSpell();
- goblin.printStatus();
+ wizard.undoLastSpell();
+ goblin.printStatus();
- wizard.redoLastSpell();
- goblin.printStatus();
+ wizard.redoLastSpell();
+ goblin.printStatus();
- wizard.redoLastSpell();
- goblin.printStatus();
- }
+ wizard.redoLastSpell();
+ goblin.printStatus();
+ }
}
diff --git a/command/src/main/java/com/iluwatar/command/Command.java b/command/src/main/java/com/iluwatar/command/Command.java
index 9ffeed24d..4b5127263 100644
--- a/command/src/main/java/com/iluwatar/command/Command.java
+++ b/command/src/main/java/com/iluwatar/command/Command.java
@@ -7,13 +7,13 @@ package com.iluwatar.command;
*/
public abstract class Command {
- public abstract void execute(Target target);
+ public abstract void execute(Target target);
- public abstract void undo();
+ public abstract void undo();
- public abstract void redo();
+ public abstract void redo();
- @Override
- public abstract String toString();
+ @Override
+ public abstract String toString();
}
diff --git a/command/src/main/java/com/iluwatar/command/Goblin.java b/command/src/main/java/com/iluwatar/command/Goblin.java
index 7d0804b0c..d5fcb7078 100644
--- a/command/src/main/java/com/iluwatar/command/Goblin.java
+++ b/command/src/main/java/com/iluwatar/command/Goblin.java
@@ -7,14 +7,14 @@ package com.iluwatar.command;
*/
public class Goblin extends Target {
- public Goblin() {
- setSize(Size.NORMAL);
- setVisibility(Visibility.VISIBLE);
- }
+ public Goblin() {
+ setSize(Size.NORMAL);
+ setVisibility(Visibility.VISIBLE);
+ }
- @Override
- public String toString() {
- return "Goblin";
- }
+ @Override
+ public String toString() {
+ return "Goblin";
+ }
}
diff --git a/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java b/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java
index b72c34cc2..02f1b1cc1 100644
--- a/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java
+++ b/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java
@@ -7,30 +7,30 @@ package com.iluwatar.command;
*/
public class InvisibilitySpell extends Command {
- private Target target;
+ private Target target;
- @Override
- public void execute(Target target) {
- target.setVisibility(Visibility.INVISIBLE);
- this.target = target;
- }
+ @Override
+ public void execute(Target target) {
+ target.setVisibility(Visibility.INVISIBLE);
+ this.target = target;
+ }
- @Override
- public void undo() {
- if (target != null) {
- target.setVisibility(Visibility.VISIBLE);
- }
- }
+ @Override
+ public void undo() {
+ if (target != null) {
+ target.setVisibility(Visibility.VISIBLE);
+ }
+ }
- @Override
- public void redo() {
- if (target != null) {
- target.setVisibility(Visibility.INVISIBLE);
- }
- }
+ @Override
+ public void redo() {
+ if (target != null) {
+ target.setVisibility(Visibility.INVISIBLE);
+ }
+ }
- @Override
- public String toString() {
- return "Invisibility spell";
- }
+ @Override
+ public String toString() {
+ return "Invisibility spell";
+ }
}
diff --git a/command/src/main/java/com/iluwatar/command/ShrinkSpell.java b/command/src/main/java/com/iluwatar/command/ShrinkSpell.java
index f36438082..46448bf6c 100644
--- a/command/src/main/java/com/iluwatar/command/ShrinkSpell.java
+++ b/command/src/main/java/com/iluwatar/command/ShrinkSpell.java
@@ -7,32 +7,32 @@ package com.iluwatar.command;
*/
public class ShrinkSpell extends Command {
- private Size oldSize;
- private Target target;
+ private Size oldSize;
+ private Target target;
- @Override
- public void execute(Target target) {
- oldSize = target.getSize();
- target.setSize(Size.SMALL);
- this.target = target;
- }
+ @Override
+ public void execute(Target target) {
+ oldSize = target.getSize();
+ target.setSize(Size.SMALL);
+ this.target = target;
+ }
- @Override
- public void undo() {
- if (oldSize != null && target != null) {
- Size temp = target.getSize();
- target.setSize(oldSize);
- oldSize = temp;
- }
- }
+ @Override
+ public void undo() {
+ if (oldSize != null && target != null) {
+ Size temp = target.getSize();
+ target.setSize(oldSize);
+ oldSize = temp;
+ }
+ }
- @Override
- public void redo() {
- undo();
- }
+ @Override
+ public void redo() {
+ undo();
+ }
- @Override
- public String toString() {
- return "Shrink spell";
- }
+ @Override
+ public String toString() {
+ return "Shrink spell";
+ }
}
diff --git a/command/src/main/java/com/iluwatar/command/Size.java b/command/src/main/java/com/iluwatar/command/Size.java
index a9c20bd59..2a443b449 100644
--- a/command/src/main/java/com/iluwatar/command/Size.java
+++ b/command/src/main/java/com/iluwatar/command/Size.java
@@ -7,16 +7,16 @@ package com.iluwatar.command;
*/
public enum Size {
- SMALL("small"), NORMAL("normal"), LARGE("large"), UNDEFINED("");
-
- private String title;
+ SMALL("small"), NORMAL("normal"), LARGE("large"), UNDEFINED("");
- Size(String title) {
- this.title = title;
- }
+ private String title;
- @Override
- public String toString() {
- return title;
- }
+ Size(String title) {
+ this.title = title;
+ }
+
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/command/src/main/java/com/iluwatar/command/Target.java b/command/src/main/java/com/iluwatar/command/Target.java
index 6ea2681d3..e12f758ff 100644
--- a/command/src/main/java/com/iluwatar/command/Target.java
+++ b/command/src/main/java/com/iluwatar/command/Target.java
@@ -7,32 +7,32 @@ package com.iluwatar.command;
*/
public abstract class Target {
- private Size size;
+ private Size size;
- private Visibility visibility;
+ private Visibility visibility;
- public Size getSize() {
- return size;
- }
+ public Size getSize() {
+ return size;
+ }
- public void setSize(Size size) {
- this.size = size;
- }
+ public void setSize(Size size) {
+ this.size = size;
+ }
- public Visibility getVisibility() {
- return visibility;
- }
+ public Visibility getVisibility() {
+ return visibility;
+ }
- public void setVisibility(Visibility visibility) {
- this.visibility = visibility;
- }
+ public void setVisibility(Visibility visibility) {
+ this.visibility = visibility;
+ }
- @Override
- public abstract String toString();
+ @Override
+ public abstract String toString();
- public void printStatus() {
- System.out.println(String.format("%s, [size=%s] [visibility=%s]", this,
- getSize(), getVisibility()));
- System.out.println();
- }
+ public void printStatus() {
+ System.out.println(String.format("%s, [size=%s] [visibility=%s]", this, getSize(),
+ getVisibility()));
+ System.out.println();
+ }
}
diff --git a/command/src/main/java/com/iluwatar/command/Visibility.java b/command/src/main/java/com/iluwatar/command/Visibility.java
index 3316ac9e3..ebf8a306c 100644
--- a/command/src/main/java/com/iluwatar/command/Visibility.java
+++ b/command/src/main/java/com/iluwatar/command/Visibility.java
@@ -7,16 +7,16 @@ package com.iluwatar.command;
*/
public enum Visibility {
- VISIBLE("visible"), INVISIBLE("invisible"), UNDEFINED("");
+ VISIBLE("visible"), INVISIBLE("invisible"), UNDEFINED("");
- private String title;
+ private String title;
- Visibility(String title) {
- this.title = title;
- }
+ Visibility(String title) {
+ this.title = title;
+ }
- @Override
- public String toString() {
- return title;
- }
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/command/src/main/java/com/iluwatar/command/Wizard.java b/command/src/main/java/com/iluwatar/command/Wizard.java
index 995b4441a..edef8d3a9 100644
--- a/command/src/main/java/com/iluwatar/command/Wizard.java
+++ b/command/src/main/java/com/iluwatar/command/Wizard.java
@@ -10,38 +10,37 @@ import java.util.LinkedList;
*/
public class Wizard {
- private Deque
- * In this example we have sentences composed of words composed of letters. All of
- * the objects can be treated through the same interface ({@link LetterComposite}).
+ * In this example we have sentences composed of words composed of letters. All of the objects can
+ * be treated through the same interface ({@link LetterComposite}).
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- System.out.println("Message from the orcs: ");
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ System.out.println("Message from the orcs: ");
- LetterComposite orcMessage = new Messenger().messageFromOrcs();
- orcMessage.print();
+ LetterComposite orcMessage = new Messenger().messageFromOrcs();
+ orcMessage.print();
- System.out.println("\n");
+ System.out.println("\n");
- System.out.println("Message from the elves: ");
+ System.out.println("Message from the elves: ");
- LetterComposite elfMessage = new Messenger().messageFromElves();
- elfMessage.print();
- }
+ LetterComposite elfMessage = new Messenger().messageFromElves();
+ elfMessage.print();
+ }
}
diff --git a/composite/src/main/java/com/iluwatar/composite/Letter.java b/composite/src/main/java/com/iluwatar/composite/Letter.java
index 8304ea801..4071eecda 100644
--- a/composite/src/main/java/com/iluwatar/composite/Letter.java
+++ b/composite/src/main/java/com/iluwatar/composite/Letter.java
@@ -7,20 +7,19 @@ package com.iluwatar.composite;
*/
public class Letter extends LetterComposite {
- private char c;
+ private char c;
- public Letter(char c) {
- this.c = c;
- }
+ public Letter(char c) {
+ this.c = c;
+ }
- @Override
- protected void printThisBefore() {
- System.out.print(c);
- }
-
- @Override
- protected void printThisAfter() {
- // nop
- }
+ @Override
+ protected void printThisBefore() {
+ System.out.print(c);
+ }
+ @Override
+ protected void printThisAfter() {
+ // nop
+ }
}
diff --git a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java
index e58d51b25..1fdf4fdb6 100644
--- a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java
+++ b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java
@@ -10,25 +10,25 @@ import java.util.List;
*/
public abstract class LetterComposite {
- private List
- * With the DAO pattern, we can use various method calls to retrieve/add/delete/update data without directly
- * interacting with the data. The below example demonstrates basic CRUD operations: select, add, update, and delete.
+ * With the DAO pattern, we can use various method calls to retrieve/add/delete/update data without
+ * directly interacting with the data. The below example demonstrates basic CRUD operations: select,
+ * add, update, and delete.
*
*/
public class App {
- private static Logger LOGGER = Logger.getLogger(App.class);
+ private static Logger LOGGER = Logger.getLogger(App.class);
- /**
- * Program entry point.
- *
- * @param args command line args.
- */
- public static void main(final String[] args) {
- final CustomerDaoImpl customerDao = new CustomerDaoImpl(generateSampleCustomers());
- LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
- LOGGER.info("customerDao.getCusterById(2): " + customerDao.getCustomerById(2));
- final Customer customer = new Customer(4, "Dan", "Danson");
- customerDao.addCustomer(customer);
- LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
- customer.setFirstName("Daniel");
- customer.setLastName("Danielson");
- customerDao.updateCustomer(customer);
- LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
- customerDao.deleteCustomer(customer);
- LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
- }
+ /**
+ * Program entry point.
+ *
+ * @param args command line args.
+ */
+ public static void main(final String[] args) {
+ final CustomerDaoImpl customerDao = new CustomerDaoImpl(generateSampleCustomers());
+ LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
+ LOGGER.info("customerDao.getCusterById(2): " + customerDao.getCustomerById(2));
+ final Customer customer = new Customer(4, "Dan", "Danson");
+ customerDao.addCustomer(customer);
+ LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
+ customer.setFirstName("Daniel");
+ customer.setLastName("Danielson");
+ customerDao.updateCustomer(customer);
+ LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
+ customerDao.deleteCustomer(customer);
+ LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
+ }
- /**
- * Generate customers.
- *
- * @return list of customers.
- */
- public static List
- * In this example we show how the simple {@link Troll} first attacks and then
- * flees the battle. Then we decorate the {@link Troll} with a {@link SmartTroll}
- * and perform the attack again. You can see how the behavior changes after the
- * decoration.
+ * In this example we show how the simple {@link Troll} first attacks and then flees the battle.
+ * Then we decorate the {@link Troll} with a {@link SmartTroll} and perform the attack again. You
+ * can see how the behavior changes after the decoration.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
- // simple troll
- System.out.println("A simple looking troll approaches.");
- Hostile troll = new Troll();
- troll.attack();
- troll.fleeBattle();
- System.out.printf("Simple troll power %d.\n", troll.getAttackPower());
+ // simple troll
+ System.out.println("A simple looking troll approaches.");
+ Hostile troll = new Troll();
+ troll.attack();
+ troll.fleeBattle();
+ System.out.printf("Simple troll power %d.\n", troll.getAttackPower());
- // change the behavior of the simple troll by adding a decorator
- System.out.println("\nA smart looking troll surprises you.");
- Hostile smart = new SmartTroll(troll);
- smart.attack();
- smart.fleeBattle();
- System.out.printf("Smart troll power %d.\n", smart.getAttackPower());
- }
+ // change the behavior of the simple troll by adding a decorator
+ System.out.println("\nA smart looking troll surprises you.");
+ Hostile smart = new SmartTroll(troll);
+ smart.attack();
+ smart.fleeBattle();
+ System.out.printf("Smart troll power %d.\n", smart.getAttackPower());
+ }
}
diff --git a/decorator/src/main/java/com/iluwatar/decorator/Hostile.java b/decorator/src/main/java/com/iluwatar/decorator/Hostile.java
index 709072501..8b8f0c255 100644
--- a/decorator/src/main/java/com/iluwatar/decorator/Hostile.java
+++ b/decorator/src/main/java/com/iluwatar/decorator/Hostile.java
@@ -7,10 +7,10 @@ package com.iluwatar.decorator;
*/
public interface Hostile {
- void attack();
+ void attack();
- int getAttackPower();
+ int getAttackPower();
- void fleeBattle();
+ void fleeBattle();
}
diff --git a/decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java b/decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java
index 909f94c95..93927237d 100644
--- a/decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java
+++ b/decorator/src/main/java/com/iluwatar/decorator/SmartTroll.java
@@ -1,36 +1,34 @@
package com.iluwatar.decorator;
/**
- * SmartTroll is a decorator for {@link Hostile} objects.
- * The calls to the {@link Hostile} interface are intercepted
- * and decorated. Finally the calls are delegated
- * to the decorated {@link Hostile} object.
+ * SmartTroll is a decorator for {@link Hostile} objects. The calls to the {@link Hostile} interface
+ * are intercepted and decorated. Finally the calls are delegated to the decorated {@link Hostile}
+ * object.
*
*/
public class SmartTroll implements Hostile {
- private Hostile decorated;
+ private Hostile decorated;
- public SmartTroll(Hostile decorated) {
- this.decorated = decorated;
- }
+ public SmartTroll(Hostile decorated) {
+ this.decorated = decorated;
+ }
- @Override
- public void attack() {
- System.out.println("The troll throws a rock at you!");
- decorated.attack();
- }
+ @Override
+ public void attack() {
+ System.out.println("The troll throws a rock at you!");
+ decorated.attack();
+ }
- @Override
- public int getAttackPower() {
- // decorated troll power + 20 because it is smart
- return decorated.getAttackPower() + 20;
- }
-
- @Override
- public void fleeBattle() {
- System.out.println("The troll calls for help!");
- decorated.fleeBattle();
- }
+ @Override
+ public int getAttackPower() {
+ // decorated troll power + 20 because it is smart
+ return decorated.getAttackPower() + 20;
+ }
+ @Override
+ public void fleeBattle() {
+ System.out.println("The troll calls for help!");
+ decorated.fleeBattle();
+ }
}
diff --git a/decorator/src/main/java/com/iluwatar/decorator/Troll.java b/decorator/src/main/java/com/iluwatar/decorator/Troll.java
index 85d873dbe..a10f76f79 100644
--- a/decorator/src/main/java/com/iluwatar/decorator/Troll.java
+++ b/decorator/src/main/java/com/iluwatar/decorator/Troll.java
@@ -7,17 +7,16 @@ package com.iluwatar.decorator;
*/
public class Troll implements Hostile {
- public void attack() {
- System.out.println("The troll swings at you with a club!");
- }
+ public void attack() {
+ System.out.println("The troll swings at you with a club!");
+ }
- @Override
- public int getAttackPower() {
- return 10;
- }
-
- public void fleeBattle() {
- System.out.println("The troll shrieks in horror and runs away!");
- }
+ @Override
+ public int getAttackPower() {
+ return 10;
+ }
+ public void fleeBattle() {
+ System.out.println("The troll shrieks in horror and runs away!");
+ }
}
diff --git a/decorator/src/test/java/com/iluwatar/decorator/AppTest.java b/decorator/src/test/java/com/iluwatar/decorator/AppTest.java
index b74bd3a06..f6fa96092 100644
--- a/decorator/src/test/java/com/iluwatar/decorator/AppTest.java
+++ b/decorator/src/test/java/com/iluwatar/decorator/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.decorator.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java
index 8202cc58e..810957858 100644
--- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java
+++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java
@@ -2,21 +2,20 @@ package com.iluwatar.dependency.injection;
/**
*
- * AdvancedWizard implements inversion of control.
- * It depends on abstraction that can be injected through
- * its constructor.
+ * AdvancedWizard implements inversion of control. It depends on abstraction that can be injected
+ * through its constructor.
*
*/
public class AdvancedWizard implements Wizard {
-
- private Tobacco tobacco;
- public AdvancedWizard(Tobacco tobacco) {
- this.tobacco = tobacco;
- }
+ private Tobacco tobacco;
- @Override
- public void smoke() {
- tobacco.smoke(this);
- }
+ public AdvancedWizard(Tobacco tobacco) {
+ this.tobacco = tobacco;
+ }
+
+ @Override
+ public void smoke() {
+ tobacco.smoke(this);
+ }
}
diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java
index a882863b7..0205724b5 100644
--- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java
+++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java
@@ -5,40 +5,41 @@ import com.google.inject.Injector;
/**
*
- * Dependency Injection pattern deals with how objects handle their dependencies. The pattern
+ * Dependency Injection pattern deals with how objects handle their dependencies. The pattern
* implements so called inversion of control principle. Inversion of control has two specific rules:
- * - High-level modules should not depend on low-level modules. Both should depend on abstractions.
- * - Abstractions should not depend on details. Details should depend on abstractions.
- *
- * In this example we show you three different wizards. The first one ({@link SimpleWizard}) is a naive
- * implementation violating the inversion of control principle. It depends directly on a concrete
- * implementation which cannot be changed.
- *
- * The second wizard ({@link AdvancedWizard}) is more flexible. It does not depend on any concrete implementation
- * but abstraction. It utilizes Dependency Injection pattern allowing its {@link Tobacco} dependency to be
- * injected through its constructor. This way, handling the dependency is no longer the wizard's
- * responsibility. It is resolved outside the wizard class.
- *
- * The third example takes the pattern a step further. It uses Guice framework for Dependency Injection.
- * {@link TobaccoModule} binds a concrete implementation to abstraction. Injector is then used to create
- * {@link GuiceWizard} object with correct dependencies.
+ * - High-level modules should not depend on low-level modules. Both should depend on abstractions.
+ * - Abstractions should not depend on details. Details should depend on abstractions.
+ *
+ * In this example we show you three different wizards. The first one ({@link SimpleWizard}) is a
+ * naive implementation violating the inversion of control principle. It depends directly on a
+ * concrete implementation which cannot be changed.
+ *
+ * The second wizard ({@link AdvancedWizard}) is more flexible. It does not depend on any concrete
+ * implementation but abstraction. It utilizes Dependency Injection pattern allowing its
+ * {@link Tobacco} dependency to be injected through its constructor. This way, handling the
+ * dependency is no longer the wizard's responsibility. It is resolved outside the wizard class.
+ *
+ * The third example takes the pattern a step further. It uses Guice framework for Dependency
+ * Injection. {@link TobaccoModule} binds a concrete implementation to abstraction. Injector is then
+ * used to create {@link GuiceWizard} object with correct dependencies.
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
- SimpleWizard simpleWizard = new SimpleWizard();
- simpleWizard.smoke();
-
- AdvancedWizard advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco());
- advancedWizard.smoke();
-
- Injector injector = Guice.createInjector(new TobaccoModule());
- GuiceWizard guiceWizard = injector.getInstance(GuiceWizard.class);
- guiceWizard.smoke();
- }
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ SimpleWizard simpleWizard = new SimpleWizard();
+ simpleWizard.smoke();
+
+ AdvancedWizard advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco());
+ advancedWizard.smoke();
+
+ Injector injector = Guice.createInjector(new TobaccoModule());
+ GuiceWizard guiceWizard = injector.getInstance(GuiceWizard.class);
+ guiceWizard.smoke();
+ }
}
diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java
index 9393377f1..e5c77ba18 100644
--- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java
+++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java
@@ -4,22 +4,21 @@ import javax.inject.Inject;
/**
*
- * GuiceWizard implements inversion of control.
- * Its dependencies are injected through its constructor
- * by Guice framework.
+ * GuiceWizard implements inversion of control. Its dependencies are injected through its
+ * constructor by Guice framework.
*
*/
public class GuiceWizard implements Wizard {
-
- private Tobacco tobacco;
-
- @Inject
- public GuiceWizard(Tobacco tobacco) {
- this.tobacco = tobacco;
- }
- @Override
- public void smoke() {
- tobacco.smoke(this);
- }
+ private Tobacco tobacco;
+
+ @Inject
+ public GuiceWizard(Tobacco tobacco) {
+ this.tobacco = tobacco;
+ }
+
+ @Override
+ public void smoke() {
+ tobacco.smoke(this);
+ }
}
diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java
index 5bc2c8377..976616e74 100644
--- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java
+++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java
@@ -2,15 +2,15 @@ package com.iluwatar.dependency.injection;
/**
*
- * Naive Wizard implementation violating the inversion of control principle.
- * It should depend on abstraction instead.
+ * Naive Wizard implementation violating the inversion of control principle. It should depend on
+ * abstraction instead.
*
*/
public class SimpleWizard implements Wizard {
-
- private OldTobyTobacco tobacco = new OldTobyTobacco();
-
- public void smoke() {
- tobacco.smoke(this);
- }
+
+ private OldTobyTobacco tobacco = new OldTobyTobacco();
+
+ public void smoke() {
+ tobacco.smoke(this);
+ }
}
diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java
index 7ee97404d..48e4cd8de 100644
--- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java
+++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java
@@ -6,8 +6,9 @@ package com.iluwatar.dependency.injection;
*
*/
public abstract class Tobacco {
-
- public void smoke(Wizard wizard) {
- System.out.println(String.format("%s smoking %s", wizard.getClass().getSimpleName(), this.getClass().getSimpleName()));
- }
+
+ public void smoke(Wizard wizard) {
+ System.out.println(String.format("%s smoking %s", wizard.getClass().getSimpleName(), this
+ .getClass().getSimpleName()));
+ }
}
diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java
index d2dd1072e..8187bae9f 100644
--- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java
+++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java
@@ -9,8 +9,8 @@ import com.google.inject.AbstractModule;
*/
public class TobaccoModule extends AbstractModule {
- @Override
- protected void configure() {
- bind(Tobacco.class).to(RivendellTobacco.class);
- }
+ @Override
+ protected void configure() {
+ bind(Tobacco.class).to(RivendellTobacco.class);
+ }
}
diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java
index 8ac9f9fcb..0376fcc2e 100644
--- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java
+++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java
@@ -6,7 +6,7 @@ package com.iluwatar.dependency.injection;
*
*/
public interface Wizard {
-
- void smoke();
+
+ void smoke();
}
diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java
index 5315fe1db..8d6411028 100644
--- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java
+++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.dependency.injection.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java
index b8d6a41a0..0cc62c995 100644
--- a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java
+++ b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java
@@ -6,38 +6,37 @@ import java.util.concurrent.TimeUnit;
/**
*
- * Double Checked Locking is a concurrency design pattern used to reduce the overhead
- * of acquiring a lock by first testing the locking criterion (the "lock hint") without
- * actually acquiring the lock. Only if the locking criterion check indicates that
- * locking is required does the actual locking logic proceed.
+ * Double Checked Locking is a concurrency design pattern used to reduce the overhead of acquiring a
+ * lock by first testing the locking criterion (the "lock hint") without actually acquiring the
+ * lock. Only if the locking criterion check indicates that locking is required does the actual
+ * locking logic proceed.
*
- * In {@link Inventory} we store the items with a given size. However, we do not store
- * more items than the inventory size. To address concurrent access problems we
- * use double checked locking to add item to inventory. In this method, the
- * thread which gets the lock first adds the item.
+ * In {@link Inventory} we store the items with a given size. However, we do not store more items
+ * than the inventory size. To address concurrent access problems we use double checked locking to
+ * add item to inventory. In this method, the thread which gets the lock first adds the item.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- final Inventory inventory = new Inventory(1000);
- ExecutorService executorService = Executors.newFixedThreadPool(3);
- for (int i = 0; i < 3; i++) {
- executorService.execute(() -> {
- while (inventory.addItem(new Item()))
- ;
- });
- }
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ final Inventory inventory = new Inventory(1000);
+ ExecutorService executorService = Executors.newFixedThreadPool(3);
+ for (int i = 0; i < 3; i++) {
+ executorService.execute(() -> {
+ while (inventory.addItem(new Item()));
+ });
+ }
- executorService.shutdown();
- try {
- executorService.awaitTermination(5, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- System.out.println("Error waiting for ExecutorService shutdown");
- }
- }
+ executorService.shutdown();
+ try {
+ executorService.awaitTermination(5, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ System.out.println("Error waiting for ExecutorService shutdown");
+ }
+ }
}
diff --git a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java
index a58926d9d..b51e000a7 100644
--- a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java
+++ b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java
@@ -12,32 +12,30 @@ import java.util.concurrent.locks.ReentrantLock;
*/
public class Inventory {
- private final int inventorySize;
- private final List
- * One way to implement this would be to create multiple instanceof-checks for the methods parameter.
- * However, this creates a maintenance issue. When new types are added we would also need to change
- * the method's implementation and add a new instanceof-check. This violates the single responsibility
- * principle - a class should have only one reason to change.
+ * One way to implement this would be to create multiple instanceof-checks for the methods
+ * parameter. However, this creates a maintenance issue. When new types are added we would also need
+ * to change the method's implementation and add a new instanceof-check. This violates the single
+ * responsibility principle - a class should have only one reason to change.
*
* Instead of the instanceof-checks a better way is to make another virtual call on the parameter
* object. This way new functionality can be easily added without the need to modify existing
* implementation (open-closed principle).
*
- * In this example we have hierarchy of objects ({@link GameObject}) that can collide to each other. Each
- * object has its own coordinates which are checked against the other objects' coordinates. If
+ * In this example we have hierarchy of objects ({@link GameObject}) that can collide to each other.
+ * Each object has its own coordinates which are checked against the other objects' coordinates. If
* there is an overlap, then the objects collide utilizing the Double Dispatch pattern.
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
- // initialize game objects and print their status
- List
- * An Event Aggregator acts as a single source of events for many objects. It registers
- * for all the events of the many objects allowing clients to register with just the aggregator.
+ * An Event Aggregator acts as a single source of events for many objects. It registers for all the
+ * events of the many objects allowing clients to register with just the aggregator.
*
* In the example {@link LordBaelish}, {@link LordVarys} and {@link Scout} deliver events to
- * {@link KingsHand}. {@link KingsHand}, the event aggregator, then delivers the events
- * to {@link KingJoffrey}.
+ * {@link KingsHand}. {@link KingsHand}, the event aggregator, then delivers the events to
+ * {@link KingJoffrey}.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
-
- KingJoffrey kingJoffrey = new KingJoffrey();
- KingsHand kingsHand = new KingsHand(kingJoffrey);
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
- List
- * In this example, we have {@link SimpleFileWriter} class that opens and closes the file
- * for the user. The user specifies only what to do with the file by providing the
- * {@link FileWriterAction} implementation.
+ * In this example, we have {@link SimpleFileWriter} class that opens and closes the file for the
+ * user. The user specifies only what to do with the file by providing the {@link FileWriterAction}
+ * implementation.
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- * @throws IOException
- */
- public static void main( String[] args ) throws IOException {
- new SimpleFileWriter("testfile.txt", new FileWriterAction() {
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ * @throws IOException
+ */
+ public static void main(String[] args) throws IOException {
- @Override
- public void writeFile(FileWriter writer) throws IOException {
- writer.write("Hello");
- writer.append(" ");
- writer.append("there!");
- }
- });
- }
+ new SimpleFileWriter("testfile.txt", new FileWriterAction() {
+
+ @Override
+ public void writeFile(FileWriter writer) throws IOException {
+ writer.write("Hello");
+ writer.append(" ");
+ writer.append("there!");
+ }
+ });
+ }
}
diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java b/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java
index 904600ec6..1477c0ae4 100644
--- a/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java
+++ b/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java
@@ -10,6 +10,6 @@ import java.io.IOException;
*/
public interface FileWriterAction {
- void writeFile(FileWriter writer) throws IOException;
-
+ void writeFile(FileWriter writer) throws IOException;
+
}
diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java b/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java
index a7ee11d15..be89ff9ce 100644
--- a/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java
+++ b/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java
@@ -5,19 +5,18 @@ import java.io.IOException;
/**
*
- * SimpleFileWriter handles opening and closing file for the user. The user
- * only has to specify what to do with the file resource through {@link FileWriterAction}
- * parameter.
+ * SimpleFileWriter handles opening and closing file for the user. The user only has to specify what
+ * to do with the file resource through {@link FileWriterAction} parameter.
*
*/
public class SimpleFileWriter {
- public SimpleFileWriter(String filename, FileWriterAction action) throws IOException {
- FileWriter writer = new FileWriter(filename);
- try {
- action.writeFile(writer);
- } finally {
- writer.close();
- }
- }
+ public SimpleFileWriter(String filename, FileWriterAction action) throws IOException {
+ FileWriter writer = new FileWriter(filename);
+ try {
+ action.writeFile(writer);
+ } finally {
+ writer.close();
+ }
+ }
}
diff --git a/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java b/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java
index 1e8a45947..9eb3dbf5f 100644
--- a/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java
+++ b/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java
@@ -15,17 +15,17 @@ import com.iluwatar.execute.around.App;
*
*/
public class AppTest {
-
- @Test
- public void test() throws IOException {
- String[] args = {};
- App.main(args);
- }
-
- @Before
- @After
- public void cleanup() {
- File file = new File("testfile.txt");
- file.delete();
- }
+
+ @Test
+ public void test() throws IOException {
+ String[] args = {};
+ App.main(args);
+ }
+
+ @Before
+ @After
+ public void cleanup() {
+ File file = new File("testfile.txt");
+ file.delete();
+ }
}
diff --git a/facade/src/main/java/com/iluwatar/facade/App.java b/facade/src/main/java/com/iluwatar/facade/App.java
index 37cda0281..bcc492e0b 100644
--- a/facade/src/main/java/com/iluwatar/facade/App.java
+++ b/facade/src/main/java/com/iluwatar/facade/App.java
@@ -2,27 +2,28 @@ package com.iluwatar.facade;
/**
*
- * The Facade design pattern is often used when a system is very complex or difficult
- * to understand because the system has a large number of interdependent classes or
- * its source code is unavailable. This pattern hides the complexities of the larger
- * system and provides a simpler interface to the client. It typically involves a single
- * wrapper class which contains a set of members required by client. These members access
- * the system on behalf of the facade client and hide the implementation details.
+ * The Facade design pattern is often used when a system is very complex or difficult to understand
+ * because the system has a large number of interdependent classes or its source code is
+ * unavailable. This pattern hides the complexities of the larger system and provides a simpler
+ * interface to the client. It typically involves a single wrapper class which contains a set of
+ * members required by client. These members access the system on behalf of the facade client and
+ * hide the implementation details.
*
- * In this example the Facade is ({@link DwarvenGoldmineFacade}) and it provides a simpler
- * interface to the goldmine subsystem.
+ * In this example the Facade is ({@link DwarvenGoldmineFacade}) and it provides a simpler interface
+ * to the goldmine subsystem.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade();
- facade.startNewDay();
- facade.digOutGold();
- facade.endDay();
- }
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade();
+ facade.startNewDay();
+ facade.digOutGold();
+ facade.endDay();
+ }
}
diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java b/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java
index 7c33fd267..d2b6f366e 100644
--- a/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java
+++ b/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java
@@ -7,14 +7,13 @@ package com.iluwatar.facade;
*/
public class DwarvenCartOperator extends DwarvenMineWorker {
- @Override
- public void work() {
- System.out.println(name() + " moves gold chunks out of the mine.");
- }
-
- @Override
- public String name() {
- return "Dwarf cart operator";
- }
+ @Override
+ public void work() {
+ System.out.println(name() + " moves gold chunks out of the mine.");
+ }
+ @Override
+ public String name() {
+ return "Dwarf cart operator";
+ }
}
diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java
index b503889b7..df5ab1356 100644
--- a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java
+++ b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java
@@ -7,14 +7,13 @@ package com.iluwatar.facade;
*/
public class DwarvenGoldDigger extends DwarvenMineWorker {
- @Override
- public void work() {
- System.out.println(name() + " digs for gold.");
- }
-
- @Override
- public String name() {
- return "Dwarf gold digger";
- }
+ @Override
+ public void work() {
+ System.out.println(name() + " digs for gold.");
+ }
+ @Override
+ public String name() {
+ return "Dwarf gold digger";
+ }
}
diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java
index 83a989fa7..d6b653eaa 100644
--- a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java
+++ b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java
@@ -6,40 +6,39 @@ import java.util.List;
/**
*
- * DwarvenGoldmineFacade provides a single interface
- * through which users can operate the subsystems.
+ * DwarvenGoldmineFacade provides a single interface through which users can operate the subsystems.
*
- * This makes the goldmine easier to operate and
- * cuts the dependencies from the goldmine user to
- * the subsystems.
+ * This makes the goldmine easier to operate and cuts the dependencies from the goldmine user to the
+ * subsystems.
*
*/
public class DwarvenGoldmineFacade {
- private final List
* In this Factory Method example we have an interface ({@link Blacksmith}) with a method for
- * creating objects ({@link Blacksmith#manufactureWeapon}). The concrete subclasses
- * ({@link OrcBlacksmith}, {@link ElfBlacksmith}) then override the method to produce
- * objects of their liking.
+ * creating objects ({@link Blacksmith#manufactureWeapon}). The concrete subclasses (
+ * {@link OrcBlacksmith}, {@link ElfBlacksmith}) then override the method to produce objects of
+ * their liking.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- Blacksmith blacksmith;
- Weapon weapon;
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ Blacksmith blacksmith;
+ Weapon weapon;
- blacksmith = new OrcBlacksmith();
- weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
- System.out.println(weapon);
- weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
- System.out.println(weapon);
+ blacksmith = new OrcBlacksmith();
+ weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
+ System.out.println(weapon);
+ weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
+ System.out.println(weapon);
- blacksmith = new ElfBlacksmith();
- weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
- System.out.println(weapon);
- weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
- System.out.println(weapon);
- }
+ blacksmith = new ElfBlacksmith();
+ weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
+ System.out.println(weapon);
+ weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
+ System.out.println(weapon);
+ }
}
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java
index 516c993a9..991a9d433 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java
@@ -7,6 +7,6 @@ package com.iluwatar.factory.method;
*/
public interface Blacksmith {
- Weapon manufactureWeapon(WeaponType weaponType);
+ Weapon manufactureWeapon(WeaponType weaponType);
}
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java
index 9a5e62890..99de5329b 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java
@@ -7,8 +7,8 @@ package com.iluwatar.factory.method;
*/
public class ElfBlacksmith implements Blacksmith {
- public Weapon manufactureWeapon(WeaponType weaponType) {
- return new ElfWeapon(weaponType);
- }
+ public Weapon manufactureWeapon(WeaponType weaponType) {
+ return new ElfWeapon(weaponType);
+ }
}
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java
index 75bb8a9e0..d2f38bc48 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java
@@ -7,15 +7,14 @@ package com.iluwatar.factory.method;
*/
public class ElfWeapon implements Weapon {
- private WeaponType weaponType;
+ private WeaponType weaponType;
- public ElfWeapon(WeaponType weaponType) {
- this.weaponType = weaponType;
- }
-
- @Override
- public String toString() {
- return "Elven " + weaponType;
- }
+ public ElfWeapon(WeaponType weaponType) {
+ this.weaponType = weaponType;
+ }
+ @Override
+ public String toString() {
+ return "Elven " + weaponType;
+ }
}
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java
index 382507ec9..c4db6c223 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java
@@ -7,8 +7,7 @@ package com.iluwatar.factory.method;
*/
public class OrcBlacksmith implements Blacksmith {
- public Weapon manufactureWeapon(WeaponType weaponType) {
- return new OrcWeapon(weaponType);
- }
-
+ public Weapon manufactureWeapon(WeaponType weaponType) {
+ return new OrcWeapon(weaponType);
+ }
}
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java
index 85500799e..48cd9c5a3 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java
@@ -7,15 +7,14 @@ package com.iluwatar.factory.method;
*/
public class OrcWeapon implements Weapon {
- private WeaponType weaponType;
+ private WeaponType weaponType;
- public OrcWeapon(WeaponType weaponType) {
- this.weaponType = weaponType;
- }
-
- @Override
- public String toString() {
- return "Orcish " + weaponType;
- }
+ public OrcWeapon(WeaponType weaponType) {
+ this.weaponType = weaponType;
+ }
+ @Override
+ public String toString() {
+ return "Orcish " + weaponType;
+ }
}
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java b/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java
index 1c0341670..4c8f83e9b 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java
@@ -7,16 +7,16 @@ package com.iluwatar.factory.method;
*/
public enum WeaponType {
- SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED("");
+ SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED("");
- private String title;
+ private String title;
- WeaponType(String title) {
- this.title = title;
- }
+ WeaponType(String title) {
+ this.title = title;
+ }
- @Override
- public String toString() {
- return title;
- }
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java
index c6db18b3e..cb48d9ad7 100644
--- a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java
+++ b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.factory.method.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java
index 7733df37d..bdff83e17 100644
--- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java
+++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java
@@ -11,13 +11,15 @@ import java.util.function.Predicate;
import static java.lang.String.valueOf;
/**
- * The Fluent Interface pattern is useful when you want to provide an easy readable, flowing API. Those
- * interfaces tend to mimic domain specific languages, so they can nearly be read as human languages.
+ * The Fluent Interface pattern is useful when you want to provide an easy readable, flowing API.
+ * Those interfaces tend to mimic domain specific languages, so they can nearly be read as human
+ * languages.
*
* In this example two implementations of a {@link FluentIterable} interface are given. The
- * {@link SimpleFluentIterable} evaluates eagerly and would be too costly for real world applications.
- * The {@link LazyFluentIterable} is evaluated on termination. Their usage is demonstrated with a
- * simple number list that is filtered, transformed and collected. The result is printed afterwards.
+ * {@link SimpleFluentIterable} evaluates eagerly and would be too costly for real world
+ * applications. The {@link LazyFluentIterable} is evaluated on termination. Their usage is
+ * demonstrated with a simple number list that is filtered, transformed and collected. The result is
+ * printed afterwards.
*
*/
public class App {
@@ -25,11 +27,9 @@ public class App {
public static void main(String[] args) {
List
- * This example has two views: menu and content. They represent typical main menu and content area of
- * a web page. When menu item is clicked it triggers events through the dispatcher. The events are
- * received and handled by the stores updating their data as needed. The stores then notify the views
- * that they should rerender themselves.
+ * This example has two views: menu and content. They represent typical main menu and content area
+ * of a web page. When menu item is clicked it triggers events through the dispatcher. The events
+ * are received and handled by the stores updating their data as needed. The stores then notify the
+ * views that they should rerender themselves.
*
* http://facebook.github.io/flux/docs/overview.html
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
-
- // initialize and wire the system
- MenuStore menuStore = new MenuStore();
- Dispatcher.getInstance().registerStore(menuStore);
- ContentStore contentStore = new ContentStore();
- Dispatcher.getInstance().registerStore(contentStore);
- MenuView menuView = new MenuView();
- menuStore.registerView(menuView);
- ContentView contentView = new ContentView();
- contentStore.registerView(contentView);
-
- // render initial view
- menuView.render();
- contentView.render();
-
- // user clicks another menu item
- // this triggers action dispatching and eventually causes views to render with new content
- menuView.itemClicked(MenuItem.COMPANY);
- }
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+
+ // initialize and wire the system
+ MenuStore menuStore = new MenuStore();
+ Dispatcher.getInstance().registerStore(menuStore);
+ ContentStore contentStore = new ContentStore();
+ Dispatcher.getInstance().registerStore(contentStore);
+ MenuView menuView = new MenuView();
+ menuStore.registerView(menuView);
+ ContentView contentView = new ContentView();
+ contentStore.registerView(contentView);
+
+ // render initial view
+ menuView.render();
+ contentView.render();
+
+ // user clicks another menu item
+ // this triggers action dispatching and eventually causes views to render with new content
+ menuView.itemClicked(MenuItem.COMPANY);
+ }
}
diff --git a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java
index 8bf03e4b0..26c836b0e 100644
--- a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java
+++ b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java
@@ -16,37 +16,36 @@ import com.iluwatar.flux.store.Store;
*
*/
public class Dispatcher {
-
- private static Dispatcher instance = new Dispatcher();
-
- private List
- * In this example {@link AlchemistShop} has great amount of potions on its shelves.
- * To fill the shelves {@link AlchemistShop} uses {@link PotionFactory} (which represents
- * the Flyweight in this example). Internally {@link PotionFactory} holds a map
- * of the potions and lazily creates new ones when requested.
+ * In this example {@link AlchemistShop} has great amount of potions on its shelves. To fill the
+ * shelves {@link AlchemistShop} uses {@link PotionFactory} (which represents the Flyweight in this
+ * example). Internally {@link PotionFactory} holds a map of the potions and lazily creates new ones
+ * when requested.
*
- * To enable safe sharing, between clients and threads, Flyweight objects must
- * be immutable. Flyweight objects are by definition value objects.
+ * To enable safe sharing, between clients and threads, Flyweight objects must be immutable.
+ * Flyweight objects are by definition value objects.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- AlchemistShop alchemistShop = new AlchemistShop();
- alchemistShop.enumerate();
- }
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ AlchemistShop alchemistShop = new AlchemistShop();
+ alchemistShop.enumerate();
+ }
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java
index a5f8f4fb8..c458e19b5 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java
@@ -7,10 +7,8 @@ package com.iluwatar.flyweight;
*/
public class HealingPotion implements Potion {
- @Override
- public void drink() {
- System.out.println("You feel healed. (Potion="
- + System.identityHashCode(this) + ")");
- }
-
+ @Override
+ public void drink() {
+ System.out.println("You feel healed. (Potion=" + System.identityHashCode(this) + ")");
+ }
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java
index 750e3c568..45034c29a 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java
@@ -7,10 +7,8 @@ package com.iluwatar.flyweight;
*/
public class HolyWaterPotion implements Potion {
- @Override
- public void drink() {
- System.out.println("You feel blessed. (Potion="
- + System.identityHashCode(this) + ")");
- }
-
+ @Override
+ public void drink() {
+ System.out.println("You feel blessed. (Potion=" + System.identityHashCode(this) + ")");
+ }
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java
index db9d261d5..ca8de16e9 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java
@@ -7,10 +7,8 @@ package com.iluwatar.flyweight;
*/
public class InvisibilityPotion implements Potion {
- @Override
- public void drink() {
- System.out.println("You become invisible. (Potion="
- + System.identityHashCode(this) + ")");
- }
-
+ @Override
+ public void drink() {
+ System.out.println("You become invisible. (Potion=" + System.identityHashCode(this) + ")");
+ }
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java
index dfcd3c38d..f1a1855f8 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java
@@ -7,10 +7,8 @@ package com.iluwatar.flyweight;
*/
public class PoisonPotion implements Potion {
- @Override
- public void drink() {
- System.out.println("Urgh! This is poisonous. (Potion="
- + System.identityHashCode(this) + ")");
- }
-
+ @Override
+ public void drink() {
+ System.out.println("Urgh! This is poisonous. (Potion=" + System.identityHashCode(this) + ")");
+ }
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java b/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java
index c4110201c..1ba72431a 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java
@@ -7,5 +7,5 @@ package com.iluwatar.flyweight;
*/
public interface Potion {
- void drink();
+ void drink();
}
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java
index 20ec110e3..8154da984 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java
@@ -5,48 +5,47 @@ import java.util.Map;
/**
*
- * PotionFactory is the Flyweight in this example.
- * It minimizes memory use by sharing object instances.
- * It holds a map of potion instances and new potions
- * are created only when none of the type already exists.
+ * PotionFactory is the Flyweight in this example. It minimizes memory use by sharing object
+ * instances. It holds a map of potion instances and new potions are created only when none of the
+ * type already exists.
*
*/
public class PotionFactory {
- private final Map
- * PROBLEM
- * INTENT
- *
- * APPLICABILITY
- *
+ * APPLICABILITY
- * IMPLEMENTATION
- *
- * On successful completion of task the result is posted back using callback method
- * {@link AsyncTask#onPostCall(Object)}, if task execution is unable to complete normally
- * due to some exception then the reason for error is posted back using callback method
- * {@link AsyncTask#onError(Throwable)}.
- *
- * NOTE: The results are posted back in the context of background thread in this implementation.
- */
- public
+ * On successful completion of task the result is posted back using callback method
+ * {@link AsyncTask#onPostCall(Object)}, if task execution is unable to complete normally due to
+ * some exception then the reason for error is posted back using callback method
+ * {@link AsyncTask#onError(Throwable)}.
+ *
+ * NOTE: The results are posted back in the context of background thread in this implementation.
+ */
+ public
- * The classic solution consists of a series of conditional checks, with any failed
- * check aborting the request. Nested if/else statements are a standard strategy,
- * but this solution leads to code fragility and a copy-and-paste style of programming,
- * because the flow of the filtering and the action of the filters is compiled into
- * the application.
+ * The classic solution consists of a series of conditional checks, with any failed check aborting
+ * the request. Nested if/else statements are a standard strategy, but this solution leads to code
+ * fragility and a copy-and-paste style of programming, because the flow of the filtering and the
+ * action of the filters is compiled into the application.
*
- * The key to solving this problem in a flexible and unobtrusive manner is to have a
- * simple mechanism for adding and removing processing components, in which each
- * component completes a specific filtering action. This is the Intercepting Filter
- * pattern in action.
+ * The key to solving this problem in a flexible and unobtrusive manner is to have a simple
+ * mechanism for adding and removing processing components, in which each component completes a
+ * specific filtering action. This is the Intercepting Filter pattern in action.
*
- * In this example we check whether the order request is valid through pre-processing
- * done via {@link Filter}. Each field has its own corresponding {@link Filter}
+ * In this example we check whether the order request is valid through pre-processing done via
+ * {@link Filter}. Each field has its own corresponding {@link Filter}
*
+ *
* @author joshzambales
*
*/
-public class App{
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- FilterManager filterManager = new FilterManager(new Target());
- filterManager.addFilter(new NameFilter());
- filterManager.addFilter(new ContactFilter());
- filterManager.addFilter(new AddressFilter());
- filterManager.addFilter(new DepositFilter());
- filterManager.addFilter(new OrderFilter());
+public class App {
- Client client = new Client();
- client.setFilterManager(filterManager);
- }
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ FilterManager filterManager = new FilterManager(new Target());
+ filterManager.addFilter(new NameFilter());
+ filterManager.addFilter(new ContactFilter());
+ filterManager.addFilter(new AddressFilter());
+ filterManager.addFilter(new DepositFilter());
+ filterManager.addFilter(new OrderFilter());
+
+ Client client = new Client();
+ client.setFilterManager(filterManager);
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java
index 0125d1b9d..02499ed0a 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java
@@ -15,93 +15,95 @@ import javax.swing.JTextField;
import javax.swing.SwingUtilities;
/**
- * The Client class is responsible for handling the input and running them through filters inside the {@link FilterManager}.
+ * The Client class is responsible for handling the input and running them through filters inside
+ * the {@link FilterManager}.
*
- * This is where {@link Filter}s come to play as the client pre-processes the request before being displayed in the {@link Target}.
+ * This is where {@link Filter}s come to play as the client pre-processes the request before being
+ * displayed in the {@link Target}.
*
* @author joshzambales
*
*/
public class Client extends JFrame {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- private FilterManager filterManager;
- private JLabel jl;
- private JTextField[] jtFields;
- private JTextArea[] jtAreas;
- private JButton clearButton, processButton;
+ private FilterManager filterManager;
+ private JLabel jl;
+ private JTextField[] jtFields;
+ private JTextArea[] jtAreas;
+ private JButton clearButton, processButton;
- public Client() {
- super("Client System");
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- setSize(300, 300);
- jl = new JLabel("RUNNING...");
- jtFields = new JTextField[3];
- for (int i = 0; i < 3; i++) {
- jtFields[i] = new JTextField();
- }
- jtAreas = new JTextArea[2];
- for (int i = 0; i < 2; i++) {
- jtAreas[i] = new JTextArea();
- }
- clearButton = new JButton("Clear");
- processButton = new JButton("Process");
+ public Client() {
+ super("Client System");
+ setDefaultCloseOperation(EXIT_ON_CLOSE);
+ setSize(300, 300);
+ jl = new JLabel("RUNNING...");
+ jtFields = new JTextField[3];
+ for (int i = 0; i < 3; i++) {
+ jtFields[i] = new JTextField();
+ }
+ jtAreas = new JTextArea[2];
+ for (int i = 0; i < 2; i++) {
+ jtAreas[i] = new JTextArea();
+ }
+ clearButton = new JButton("Clear");
+ processButton = new JButton("Process");
- setup();
- }
+ setup();
+ }
- private void setup() {
- setLayout(new BorderLayout());
- JPanel panel = new JPanel();
- add(jl, BorderLayout.SOUTH);
- add(panel, BorderLayout.CENTER);
- panel.setLayout(new GridLayout(6, 2));
- panel.add(new JLabel("Name"));
- panel.add(jtFields[0]);
- panel.add(new JLabel("Contact Number"));
- panel.add(jtFields[1]);
- panel.add(new JLabel("Address"));
- panel.add(jtAreas[0]);
- panel.add(new JLabel("Deposit Number"));
- panel.add(jtFields[2]);
- panel.add(new JLabel("Order"));
- panel.add(jtAreas[1]);
- panel.add(clearButton);
- panel.add(processButton);
+ private void setup() {
+ setLayout(new BorderLayout());
+ JPanel panel = new JPanel();
+ add(jl, BorderLayout.SOUTH);
+ add(panel, BorderLayout.CENTER);
+ panel.setLayout(new GridLayout(6, 2));
+ panel.add(new JLabel("Name"));
+ panel.add(jtFields[0]);
+ panel.add(new JLabel("Contact Number"));
+ panel.add(jtFields[1]);
+ panel.add(new JLabel("Address"));
+ panel.add(jtAreas[0]);
+ panel.add(new JLabel("Deposit Number"));
+ panel.add(jtFields[2]);
+ panel.add(new JLabel("Order"));
+ panel.add(jtAreas[1]);
+ panel.add(clearButton);
+ panel.add(processButton);
- clearButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- for (JTextArea i : jtAreas) {
- i.setText("");
- }
- for (JTextField i : jtFields) {
- i.setText("");
- }
- }
- });
+ clearButton.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ for (JTextArea i : jtAreas) {
+ i.setText("");
+ }
+ for (JTextField i : jtFields) {
+ i.setText("");
+ }
+ }
+ });
- processButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- Order order = new Order(jtFields[0].getText(), jtFields[1]
- .getText(), jtAreas[0].getText(),
- jtFields[2].getText(), jtAreas[1].getText());
- jl.setText(sendRequest(order));
- }
- });
+ processButton.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ Order order =
+ new Order(jtFields[0].getText(), jtFields[1].getText(), jtAreas[0].getText(),
+ jtFields[2].getText(), jtAreas[1].getText());
+ jl.setText(sendRequest(order));
+ }
+ });
- JRootPane rootPane = SwingUtilities.getRootPane(processButton);
- rootPane.setDefaultButton(processButton);
- setVisible(true);
- }
+ JRootPane rootPane = SwingUtilities.getRootPane(processButton);
+ rootPane.setDefaultButton(processButton);
+ setVisible(true);
+ }
- public void setFilterManager(FilterManager filterManager) {
- this.filterManager = filterManager;
- }
+ public void setFilterManager(FilterManager filterManager) {
+ this.filterManager = filterManager;
+ }
- public String sendRequest(Order order) {
- return filterManager.filterRequest(order);
- }
+ public String sendRequest(Order order) {
+ return filterManager.filterRequest(order);
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java
index 214376263..9d5ff1336 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java
@@ -1,24 +1,24 @@
package com.iluwatar.intercepting.filter;
/**
- * Concrete implementation of filter
- * This filter checks for the contact field in which it checks if the input consist of numbers
- * and it also checks if the input follows the length constraint (11 digits)
+ * Concrete implementation of filter This filter checks for the contact field in which it checks if
+ * the input consist of numbers and it also checks if the input follows the length constraint (11
+ * digits)
+ *
* @author joshzambales
*
*/
public class ContactFilter extends AbstractFilter {
-
- @Override
- public String execute(Order order) {
- String result = super.execute(order);
- if (order.getContactNumber() == null
- || order.getContactNumber().isEmpty()
- || order.getContactNumber().matches(".*[^\\d]+.*")
- || order.getContactNumber().length() != 11) {
- return result + "Invalid contact number! ";
- } else {
- return result;
- }
- }
+
+ @Override
+ public String execute(Order order) {
+ String result = super.execute(order);
+ if (order.getContactNumber() == null || order.getContactNumber().isEmpty()
+ || order.getContactNumber().matches(".*[^\\d]+.*")
+ || order.getContactNumber().length() != 11) {
+ return result + "Invalid contact number! ";
+ } else {
+ return result;
+ }
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java
index 129c07cd7..62bc600f3 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java
@@ -1,20 +1,20 @@
package com.iluwatar.intercepting.filter;
/**
- * Concrete implementation of filter
- * This checks for the deposit code
+ * Concrete implementation of filter This checks for the deposit code
+ *
* @author joshzambales
*
*/
public class DepositFilter extends AbstractFilter {
-
- @Override
- public String execute(Order order) {
- String result = super.execute(order);
- if (order.getDepositNumber() == null || order.getDepositNumber().isEmpty()) {
- return result + "Invalid deposit number! ";
- } else {
- return result;
- }
- }
+
+ @Override
+ public String execute(Order order) {
+ String result = super.execute(order);
+ if (order.getDepositNumber() == null || order.getDepositNumber().isEmpty()) {
+ return result + "Invalid deposit number! ";
+ } else {
+ return result;
+ }
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java
index a71be5154..9496bde36 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java
@@ -1,37 +1,40 @@
package com.iluwatar.intercepting.filter;
/**
- * Filters perform certain tasks prior or after execution of
- * request by request handler. In this case, before the request is handled by
- * the target, the request undergoes through each Filter
+ * Filters perform certain tasks prior or after execution of request by request handler. In this
+ * case, before the request is handled by the target, the request undergoes through each Filter
*
* @author joshzambales
*
*/
public interface Filter {
-
- /**
- * Execute order processing filter.
- * @param order
- * @return empty string on success, otherwise error message.
- */
- String execute(Order order);
-
- /**
- * Set next filter in chain after this.
- * @param filter
- */
- void setNext(Filter filter);
-
- /**
- * Get next filter in chain after this.
- * @return
- */
- Filter getNext();
-
- /**
- * Get last filter in the chain.
- * @return
- */
- Filter getLast();
+
+ /**
+ * Execute order processing filter.
+ *
+ * @param order
+ * @return empty string on success, otherwise error message.
+ */
+ String execute(Order order);
+
+ /**
+ * Set next filter in chain after this.
+ *
+ * @param filter
+ */
+ void setNext(Filter filter);
+
+ /**
+ * Get next filter in chain after this.
+ *
+ * @return
+ */
+ Filter getNext();
+
+ /**
+ * Get last filter in the chain.
+ *
+ * @return
+ */
+ Filter getLast();
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java
index e11a58ea0..987678cc7 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java
@@ -1,34 +1,34 @@
- package com.iluwatar.intercepting.filter;
-
-
+package com.iluwatar.intercepting.filter;
+
+
/**
* Filter Chain carries multiple filters and help to execute them in defined order on target.
*
* @author joshzambales
*/
public class FilterChain {
-
- private Filter chain;
-
- private final Target target;
- public FilterChain(Target target) {
- this.target = target;
- }
+ private Filter chain;
- public void addFilter(Filter filter) {
- if (chain == null) {
- chain = filter;
- } else {
- chain.getLast().setNext(filter);
- }
- }
+ private final Target target;
- public String execute(Order order) {
- if (chain != null) {
- return chain.execute(order);
- } else {
- return "RUNNING...";
- }
- }
+ public FilterChain(Target target) {
+ this.target = target;
+ }
+
+ public void addFilter(Filter filter) {
+ if (chain == null) {
+ chain = filter;
+ } else {
+ chain.getLast().setNext(filter);
+ }
+ }
+
+ public String execute(Order order) {
+ if (chain != null) {
+ return chain.execute(order);
+ } else {
+ return "RUNNING...";
+ }
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java
index d15df424a..7cdaab103 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java
@@ -7,18 +7,18 @@ package com.iluwatar.intercepting.filter;
*
*/
public class FilterManager {
-
- private FilterChain filterChain;
- public FilterManager(Target target) {
- filterChain = new FilterChain(target);
- }
+ private FilterChain filterChain;
- public void addFilter(Filter filter) {
- filterChain.addFilter(filter);
- }
+ public FilterManager(Target target) {
+ filterChain = new FilterChain(target);
+ }
- public String filterRequest(Order order) {
- return filterChain.execute(order);
- }
+ public void addFilter(Filter filter) {
+ filterChain.addFilter(filter);
+ }
+
+ public String filterRequest(Order order) {
+ return filterChain.execute(order);
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java
index 201c68bca..a458e475b 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java
@@ -1,21 +1,22 @@
package com.iluwatar.intercepting.filter;
/**
- * Concrete implementation of filter. This filter checks if the input in the Name
- * field is valid. (alphanumeric)
+ * Concrete implementation of filter. This filter checks if the input in the Name field is valid.
+ * (alphanumeric)
*
* @author joshzambales
*
*/
public class NameFilter extends AbstractFilter {
-
- @Override
- public String execute(Order order) {
- String result = super.execute(order);
- if (order.getName() == null || order.getName().isEmpty() || order.getName().matches(".*[^\\w|\\s]+.*")) {
- return result + "Invalid order! ";
- } else {
- return result;
- }
- }
+
+ @Override
+ public String execute(Order order) {
+ String result = super.execute(order);
+ if (order.getName() == null || order.getName().isEmpty()
+ || order.getName().matches(".*[^\\w|\\s]+.*")) {
+ return result + "Invalid order! ";
+ } else {
+ return result;
+ }
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java
index 60bf21f8e..5b30fee35 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java
@@ -6,60 +6,59 @@ package com.iluwatar.intercepting.filter;
*/
public class Order {
- private String name;
- private String contactNumber;
- private String address;
- private String depositNumber;
- private String order;
-
- public Order() {
- }
+ private String name;
+ private String contactNumber;
+ private String address;
+ private String depositNumber;
+ private String order;
- public Order(String name, String contactNumber, String address, String depositNumber, String order) {
- this.name = name;
- this.contactNumber = contactNumber;
- this.address = address;
- this.depositNumber = depositNumber;
- this.order = order;
- }
-
- public String getName() {
- return name;
- }
+ public Order() {}
- public void setName(String name) {
- this.name = name;
- }
+ public Order(String name, String contactNumber, String address, String depositNumber, String order) {
+ this.name = name;
+ this.contactNumber = contactNumber;
+ this.address = address;
+ this.depositNumber = depositNumber;
+ this.order = order;
+ }
- public String getContactNumber() {
- return contactNumber;
- }
+ public String getName() {
+ return name;
+ }
- public void setContactNumber(String contactNumber) {
- this.contactNumber = contactNumber;
- }
+ public void setName(String name) {
+ this.name = name;
+ }
- public String getAddress() {
- return address;
- }
+ public String getContactNumber() {
+ return contactNumber;
+ }
- public void setAddress(String address) {
- this.address = address;
- }
+ public void setContactNumber(String contactNumber) {
+ this.contactNumber = contactNumber;
+ }
- public String getDepositNumber() {
- return depositNumber;
- }
+ public String getAddress() {
+ return address;
+ }
- public void setDepositNumber(String depositNumber) {
- this.depositNumber = depositNumber;
- }
+ public void setAddress(String address) {
+ this.address = address;
+ }
- public String getOrder() {
- return order;
- }
+ public String getDepositNumber() {
+ return depositNumber;
+ }
- public void setOrder(String order) {
- this.order = order;
- }
+ public void setDepositNumber(String depositNumber) {
+ this.depositNumber = depositNumber;
+ }
+
+ public String getOrder() {
+ return order;
+ }
+
+ public void setOrder(String order) {
+ this.order = order;
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java
index cdeaec6e0..724359927 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java
@@ -7,14 +7,14 @@ package com.iluwatar.intercepting.filter;
*
*/
public class OrderFilter extends AbstractFilter {
-
- @Override
- public String execute(Order order) {
- String result = super.execute(order);
- if (order.getOrder() == null || order.getOrder().isEmpty()) {
- return result + "Invalid order! ";
- } else {
- return result;
- }
- }
+
+ @Override
+ public String execute(Order order) {
+ String result = super.execute(order);
+ if (order.getOrder() == null || order.getOrder().isEmpty()) {
+ return result + "Invalid order! ";
+ } else {
+ return result;
+ }
+ }
}
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java
index 6ca456512..cb96cd6e0 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java
@@ -22,57 +22,57 @@ import javax.swing.table.DefaultTableModel;
*/
public class Target extends JFrame {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- private JTable jt;
- private JScrollPane jsp;
- private DefaultTableModel dtm;
- private JButton del;
+ private JTable jt;
+ private JScrollPane jsp;
+ private DefaultTableModel dtm;
+ private JButton del;
- public Target() {
- super("Order System");
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- setSize(640, 480);
- dtm = new DefaultTableModel(new Object[] { "Name", "Contact Number",
- "Address", "Deposit Number", "Order" }, 0);
- jt = new JTable(dtm);
- del = new JButton("Delete");
- setup();
- }
+ public Target() {
+ super("Order System");
+ setDefaultCloseOperation(EXIT_ON_CLOSE);
+ setSize(640, 480);
+ dtm =
+ new DefaultTableModel(new Object[] {"Name", "Contact Number", "Address", "Deposit Number",
+ "Order"}, 0);
+ jt = new JTable(dtm);
+ del = new JButton("Delete");
+ setup();
+ }
- private void setup() {
- setLayout(new BorderLayout());
- JPanel bot = new JPanel();
- add(jt.getTableHeader(), BorderLayout.NORTH);
- bot.setLayout(new BorderLayout());
- bot.add(del, BorderLayout.EAST);
- add(bot, BorderLayout.SOUTH);
- jsp = new JScrollPane(jt);
- jsp.setPreferredSize(new Dimension(500, 250));
- add(jsp, BorderLayout.CENTER);
+ private void setup() {
+ setLayout(new BorderLayout());
+ JPanel bot = new JPanel();
+ add(jt.getTableHeader(), BorderLayout.NORTH);
+ bot.setLayout(new BorderLayout());
+ bot.add(del, BorderLayout.EAST);
+ add(bot, BorderLayout.SOUTH);
+ jsp = new JScrollPane(jt);
+ jsp.setPreferredSize(new Dimension(500, 250));
+ add(jsp, BorderLayout.CENTER);
- del.addActionListener(new DListener());
+ del.addActionListener(new DListener());
- JRootPane rootPane = SwingUtilities.getRootPane(del);
- rootPane.setDefaultButton(del);
- setVisible(true);
- }
+ JRootPane rootPane = SwingUtilities.getRootPane(del);
+ rootPane.setDefaultButton(del);
+ setVisible(true);
+ }
- public void execute(String[] request) {
- dtm.addRow(new Object[] { request[0], request[1], request[2],
- request[3], request[4] });
- }
+ public void execute(String[] request) {
+ dtm.addRow(new Object[] {request[0], request[1], request[2], request[3], request[4]});
+ }
- class DListener implements ActionListener {
- @Override
- public void actionPerformed(ActionEvent e) {
- int temp = jt.getSelectedRow();
- if (temp == -1)
- return;
- int temp2 = jt.getSelectedRowCount();
- for (int i = 0; i < temp2; i++) {
- dtm.removeRow(temp);
- }
- }
- }
+ class DListener implements ActionListener {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ int temp = jt.getSelectedRow();
+ if (temp == -1)
+ return;
+ int temp2 = jt.getSelectedRowCount();
+ for (int i = 0; i < temp2; i++) {
+ dtm.removeRow(temp);
+ }
+ }
+ }
}
diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java
index 9d31127a2..bcdf7c09b 100644
--- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java
+++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java
@@ -11,9 +11,9 @@ import com.iluwatar.intercepting.filter.App;
*/
public class AppTest {
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/App.java b/interpreter/src/main/java/com/iluwatar/interpreter/App.java
index 955563915..2f88951f1 100644
--- a/interpreter/src/main/java/com/iluwatar/interpreter/App.java
+++ b/interpreter/src/main/java/com/iluwatar/interpreter/App.java
@@ -4,75 +4,66 @@ import java.util.Stack;
/**
*
- * The Interpreter pattern is a design pattern that specifies how to evaluate sentences
- * in a language. The basic idea is to have a class for each symbol (terminal or nonterminal)
- * in a specialized computer language. The syntax tree of a sentence in the language is an
- * instance of the composite pattern and is used to evaluate (interpret) the sentence for a
- * client.
+ * The Interpreter pattern is a design pattern that specifies how to evaluate sentences in a
+ * language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a
+ * specialized computer language. The syntax tree of a sentence in the language is an instance of
+ * the composite pattern and is used to evaluate (interpret) the sentence for a client.
*
- * In this example we use the Interpreter pattern to break sentences into expressions
- * ({@link Expression}) that can be evaluated and as a whole form the result.
+ * In this example we use the Interpreter pattern to break sentences into expressions (
+ * {@link Expression}) that can be evaluated and as a whole form the result.
*
*/
public class App {
- /**
- *
- * Program entry point.
- *
- * Expressions can be evaluated using prefix, infix or postfix notations
- * This sample uses postfix, where operator comes after the operands
- *
- * @param args command line args
- *
- */
- public static void main(String[] args) {
- String tokenString = "4 3 2 - 1 + *";
- Stack
+ * Expressions can be evaluated using prefix, infix or postfix notations This sample uses postfix,
+ * where operator comes after the operands
+ *
+ * @param args command line args
+ *
+ */
+ public static void main(String[] args) {
+ String tokenString = "4 3 2 - 1 + *";
+ Stack
- * In this example the Iterator ({@link ItemIterator}) adds abstraction layer on
- * top of a collection ({@link TreasureChest}). This way the collection can change
- * its internal implementation without affecting its clients.
+ * In this example the Iterator ({@link ItemIterator}) adds abstraction layer on top of a collection
+ * ({@link TreasureChest}). This way the collection can change its internal implementation without
+ * affecting its clients.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- TreasureChest chest = new TreasureChest();
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ TreasureChest chest = new TreasureChest();
- ItemIterator ringIterator = chest.Iterator(ItemType.RING);
- while (ringIterator.hasNext()) {
- System.out.println(ringIterator.next());
- }
+ ItemIterator ringIterator = chest.Iterator(ItemType.RING);
+ while (ringIterator.hasNext()) {
+ System.out.println(ringIterator.next());
+ }
- System.out.println("----------");
+ System.out.println("----------");
- ItemIterator potionIterator = chest.Iterator(ItemType.POTION);
- while (potionIterator.hasNext()) {
- System.out.println(potionIterator.next());
- }
+ ItemIterator potionIterator = chest.Iterator(ItemType.POTION);
+ while (potionIterator.hasNext()) {
+ System.out.println(potionIterator.next());
+ }
- System.out.println("----------");
+ System.out.println("----------");
- ItemIterator weaponIterator = chest.Iterator(ItemType.WEAPON);
- while (weaponIterator.hasNext()) {
- System.out.println(weaponIterator.next());
- }
+ ItemIterator weaponIterator = chest.Iterator(ItemType.WEAPON);
+ while (weaponIterator.hasNext()) {
+ System.out.println(weaponIterator.next());
+ }
- System.out.println("----------");
+ System.out.println("----------");
- ItemIterator it = chest.Iterator(ItemType.ANY);
- while (it.hasNext()) {
- System.out.println(it.next());
- }
- }
+ ItemIterator it = chest.Iterator(ItemType.ANY);
+ while (it.hasNext()) {
+ System.out.println(it.next());
+ }
+ }
}
diff --git a/iterator/src/main/java/com/iluwatar/iterator/Item.java b/iterator/src/main/java/com/iluwatar/iterator/Item.java
index 4df167c6f..6492fd9ab 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/Item.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/Item.java
@@ -7,24 +7,24 @@ package com.iluwatar.iterator;
*/
public class Item {
- private ItemType type;
- private String name;
+ private ItemType type;
+ private String name;
- public Item(ItemType type, String name) {
- this.setType(type);
- this.name = name;
- }
+ public Item(ItemType type, String name) {
+ this.setType(type);
+ this.name = name;
+ }
- @Override
- public String toString() {
- return name;
- }
+ @Override
+ public String toString() {
+ return name;
+ }
- public ItemType getType() {
- return type;
- }
+ public ItemType getType() {
+ return type;
+ }
- public void setType(ItemType type) {
- this.type = type;
- }
+ public void setType(ItemType type) {
+ this.type = type;
+ }
}
diff --git a/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java b/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java
index 91b5b62c0..3798bbd74 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java
@@ -7,7 +7,7 @@ package com.iluwatar.iterator;
*/
public interface ItemIterator {
- boolean hasNext();
+ boolean hasNext();
- Item next();
+ Item next();
}
diff --git a/iterator/src/main/java/com/iluwatar/iterator/ItemType.java b/iterator/src/main/java/com/iluwatar/iterator/ItemType.java
index 288590c31..3a51c3946 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/ItemType.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/ItemType.java
@@ -7,6 +7,6 @@ package com.iluwatar.iterator;
*/
public enum ItemType {
- ANY, WEAPON, RING, POTION
+ ANY, WEAPON, RING, POTION
}
diff --git a/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java b/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java
index f4e1337bc..02496e33c 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java
@@ -10,30 +10,30 @@ import java.util.List;
*/
public class TreasureChest {
- private List
- * This example demonstrates a traditional 3-layer architecture consisting of data access
- * layer, business layer and presentation layer.
+ * This example demonstrates a traditional 3-layer architecture consisting of data access layer,
+ * business layer and presentation layer.
*
- * The data access layer is formed of Spring Data repositories
- * The business layer is built on top of the data access layer.
- * The presentation layer is built on the business layer and in this example it simply lists
- * the cakes that have been baked.
+ * The presentation layer is built on the business layer and in this example it simply lists the
+ * cakes that have been baked.
*
- * We have applied so called strict layering which means that the layers can only access
- * the classes directly beneath them. This leads the solution to create an additional set of
- * DTOs (
- * This example shows different implementations of the pattern
- * with increasing sophistication.
+ * This example shows different implementations of the pattern with increasing sophistication.
*
* Additional information and lazy loading flavours are described in
* http://martinfowler.com/eaaCatalog/lazyLoad.html
*
*/
-public class App
-{
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
-
- // Simple lazy loader - not thread safe
- HolderNaive holderNaive = new HolderNaive();
- Heavy heavy = holderNaive.getHeavy();
- System.out.println("heavy=" + heavy);
-
- // Thread safe lazy loader, but with heavy synchronization on each access
- HolderThreadSafe holderThreadSafe = new HolderThreadSafe();
- Heavy another = holderThreadSafe.getHeavy();
- System.out.println("another=" + another);
-
- // The most efficient lazy loader utilizing Java 8 features
- Java8Holder java8Holder = new Java8Holder();
- Heavy next = java8Holder.getHeavy();
- System.out.println("next=" + next);
- }
+public class App {
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+
+ // Simple lazy loader - not thread safe
+ HolderNaive holderNaive = new HolderNaive();
+ Heavy heavy = holderNaive.getHeavy();
+ System.out.println("heavy=" + heavy);
+
+ // Thread safe lazy loader, but with heavy synchronization on each access
+ HolderThreadSafe holderThreadSafe = new HolderThreadSafe();
+ Heavy another = holderThreadSafe.getHeavy();
+ System.out.println("another=" + another);
+
+ // The most efficient lazy loader utilizing Java 8 features
+ Java8Holder java8Holder = new Java8Holder();
+ Heavy next = java8Holder.getHeavy();
+ System.out.println("next=" + next);
+ }
}
diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java
index c2715434f..25e46d8b9 100644
--- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java
+++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java
@@ -7,13 +7,13 @@ package com.iluwatar.lazy.loading;
*/
public class Heavy {
- public Heavy() {
- System.out.println("Creating Heavy ...");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("... Heavy created");
- }
+ public Heavy() {
+ System.out.println("Creating Heavy ...");
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ System.out.println("... Heavy created");
+ }
}
diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java
index 1421d4b23..132ebaa5f 100644
--- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java
+++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java
@@ -2,22 +2,21 @@ package com.iluwatar.lazy.loading;
/**
*
- * Simple implementation of the lazy loading idiom.
- * However, this is not thread safe.
+ * Simple implementation of the lazy loading idiom. However, this is not thread safe.
*
*/
public class HolderNaive {
-
- private Heavy heavy;
-
- public HolderNaive() {
- System.out.println("HolderNaive created");
- }
- public Heavy getHeavy() {
- if (heavy == null) {
- heavy = new Heavy();
- }
- return heavy;
- }
+ private Heavy heavy;
+
+ public HolderNaive() {
+ System.out.println("HolderNaive created");
+ }
+
+ public Heavy getHeavy() {
+ if (heavy == null) {
+ heavy = new Heavy();
+ }
+ return heavy;
+ }
}
diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java
index cc039d9f0..d2b15a3af 100644
--- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java
+++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java
@@ -2,23 +2,22 @@ package com.iluwatar.lazy.loading;
/**
*
- * Same as HolderNaive but with added synchronization.
- * This implementation is thread safe, but each {@link #getHeavy()}
- * call costs additional synchronization overhead.
+ * Same as HolderNaive but with added synchronization. This implementation is thread safe, but each
+ * {@link #getHeavy()} call costs additional synchronization overhead.
*
*/
public class HolderThreadSafe {
-
- private Heavy heavy;
-
- public HolderThreadSafe() {
- System.out.println("HolderThreadSafe created");
- }
- public synchronized Heavy getHeavy() {
- if (heavy == null) {
- heavy = new Heavy();
- }
- return heavy;
- }
+ private Heavy heavy;
+
+ public HolderThreadSafe() {
+ System.out.println("HolderThreadSafe created");
+ }
+
+ public synchronized Heavy getHeavy() {
+ if (heavy == null) {
+ heavy = new Heavy();
+ }
+ return heavy;
+ }
}
diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java
index a03aae352..da021e014 100644
--- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java
+++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java
@@ -4,31 +4,34 @@ import java.util.function.Supplier;
/**
*
- * This lazy loader is thread safe and more efficient than {@link HolderThreadSafe}.
- * It utilizes Java 8 functional interface {@link Supplier
- * Usually a program is made up of a large number of classes. So the logic and
- * computation is distributed among these classes. However, as more classes are
- * developed in a program, especially during maintenance and/or refactoring,
- * the problem of communication between these classes may become more complex.
- * This makes the program harder to read and maintain. Furthermore, it can become
- * difficult to change the program, since any change may affect code in several
- * other classes.
+ * Usually a program is made up of a large number of classes. So the logic and computation is
+ * distributed among these classes. However, as more classes are developed in a program, especially
+ * during maintenance and/or refactoring, the problem of communication between these classes may
+ * become more complex. This makes the program harder to read and maintain. Furthermore, it can
+ * become difficult to change the program, since any change may affect code in several other
+ * classes.
*
- * With the Mediator pattern, communication between objects is encapsulated with
- * a mediator object. Objects no longer communicate directly with each other, but
- * instead communicate through the mediator. This reduces the dependencies between
- * communicating objects, thereby lowering the coupling.
+ * With the Mediator pattern, communication between objects is encapsulated with a mediator object.
+ * Objects no longer communicate directly with each other, but instead communicate through the
+ * mediator. This reduces the dependencies between communicating objects, thereby lowering the
+ * coupling.
*
- * In this example the mediator encapsulates how a set of objects ({@link PartyMember})
- * interact. Instead of referring to each other directly they use the mediator
- * ({@link Party}) interface.
+ * In this example the mediator encapsulates how a set of objects ({@link PartyMember}) interact.
+ * Instead of referring to each other directly they use the mediator ({@link Party}) interface.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
-
- // create party and members
- Party party = new PartyImpl();
- Hobbit hobbit = new Hobbit();
- Wizard wizard = new Wizard();
- Rogue rogue = new Rogue();
- Hunter hunter = new Hunter();
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
- // add party members
- party.addMember(hobbit);
- party.addMember(wizard);
- party.addMember(rogue);
- party.addMember(hunter);
+ // create party and members
+ Party party = new PartyImpl();
+ Hobbit hobbit = new Hobbit();
+ Wizard wizard = new Wizard();
+ Rogue rogue = new Rogue();
+ Hunter hunter = new Hunter();
- // perform actions -> the other party members
- // are notified by the party
- hobbit.act(Action.ENEMY);
- wizard.act(Action.TALE);
- rogue.act(Action.GOLD);
- hunter.act(Action.HUNT);
- }
+ // add party members
+ party.addMember(hobbit);
+ party.addMember(wizard);
+ party.addMember(rogue);
+ party.addMember(hunter);
+
+ // perform actions -> the other party members
+ // are notified by the party
+ hobbit.act(Action.ENEMY);
+ wizard.act(Action.TALE);
+ rogue.act(Action.GOLD);
+ hunter.act(Action.HUNT);
+ }
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java b/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java
index 5981a34a8..3d1bf83bf 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java
@@ -7,9 +7,9 @@ package com.iluwatar.mediator;
*/
public class Hobbit extends PartyMemberBase {
- @Override
- public String toString() {
- return "Hobbit";
- }
+ @Override
+ public String toString() {
+ return "Hobbit";
+ }
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Hunter.java b/mediator/src/main/java/com/iluwatar/mediator/Hunter.java
index 1487c836e..d6abf3416 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Hunter.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Hunter.java
@@ -7,9 +7,8 @@ package com.iluwatar.mediator;
*/
public class Hunter extends PartyMemberBase {
- @Override
- public String toString() {
- return "Hunter";
- }
-
+ @Override
+ public String toString() {
+ return "Hunter";
+ }
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Party.java b/mediator/src/main/java/com/iluwatar/mediator/Party.java
index 9328cdaa2..cb53dae27 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Party.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Party.java
@@ -7,8 +7,8 @@ package com.iluwatar.mediator;
*/
public interface Party {
- void addMember(PartyMember member);
+ void addMember(PartyMember member);
- void act(PartyMember actor, Action action);
+ void act(PartyMember actor, Action action);
}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java
index 5548f5163..acc70a0e6 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java
@@ -10,24 +10,24 @@ import java.util.List;
*/
public class PartyImpl implements Party {
- private final List
- * The Memento pattern is implemented with three objects: the originator, a caretaker and
- * a memento. The originator is some object that has an internal state. The caretaker is
- * going to do something to the originator, but wants to be able to undo the change. The
- * caretaker first asks the originator for a memento object. Then it does whatever operation
- * (or sequence of operations) it was going to do. To roll back to the state before the
- * operations, it returns the memento object to the originator. The memento object itself
- * is an opaque object (one which the caretaker cannot, or should not, change). When using
- * this pattern, care should be taken if the originator may change other objects or
- * resources - the memento pattern operates on a single object.
+ * The Memento pattern is implemented with three objects: the originator, a caretaker and a memento.
+ * The originator is some object that has an internal state. The caretaker is going to do something
+ * to the originator, but wants to be able to undo the change. The caretaker first asks the
+ * originator for a memento object. Then it does whatever operation (or sequence of operations) it
+ * was going to do. To roll back to the state before the operations, it returns the memento object
+ * to the originator. The memento object itself is an opaque object (one which the caretaker cannot,
+ * or should not, change). When using this pattern, care should be taken if the originator may
+ * change other objects or resources - the memento pattern operates on a single object.
*
- * In this example the object ({@link Star})
- * gives out a "memento" ({@link StarMemento}) that contains the state of the object.
- * Later on the memento can be set back to the object restoring the state.
+ * In this example the object ({@link Star}) gives out a "memento" ({@link StarMemento}) that
+ * contains the state of the object. Later on the memento can be set back to the object restoring
+ * the state.
*
*/
public class App {
- public static void main(String[] args) {
- Stack
- * The sending application doesn't necessarily know what particular application
- * will end up retrieving it, but it can be assured that the application that
- * retrieves the information is interested in that information. This is because
- * the messaging system has different Message Channels for different types of
- * information the applications want to communicate. When an application sends
- * information, it doesn't randomly add the information to any channel available;
- * it adds it to a channel whose specific purpose is to communicate that sort of
- * information. Likewise, an application that wants to receive particular information
- * doesn't pull info off some random channel; it selects what channel to get information
- * from based on what type of information it wants.
+ * The sending application doesn't necessarily know what particular application will end up
+ * retrieving it, but it can be assured that the application that retrieves the information is
+ * interested in that information. This is because the messaging system has different Message
+ * Channels for different types of information the applications want to communicate. When an
+ * application sends information, it doesn't randomly add the information to any channel available;
+ * it adds it to a channel whose specific purpose is to communicate that sort of information.
+ * Likewise, an application that wants to receive particular information doesn't pull info off some
+ * random channel; it selects what channel to get information from based on what type of information
+ * it wants.
*
- * In this example we use Apache Camel to establish two different Message Channels. The first
- * one reads from standard input and delivers messages to Direct endpoint. The second Message
- * Channel is established from the Direct component to console output. No actual messages are sent,
- * only the established routes are printed to standard output.
+ * In this example we use Apache Camel to establish two different Message Channels. The first one
+ * reads from standard input and delivers messages to Direct endpoint. The second Message Channel is
+ * established from the Direct component to console output. No actual messages are sent, only the
+ * established routes are printed to standard output.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- CamelContext context = new DefaultCamelContext();
-
- context.addRoutes(new RouteBuilder() {
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ * @throws Exception
+ */
+ public static void main(String[] args) throws Exception {
+ CamelContext context = new DefaultCamelContext();
- @Override
- public void configure() throws Exception {
- from("stream:in").to("direct:greetings");
- from("direct:greetings").to("stream:out");
- }
- });
-
- context.start();
- context.getRoutes().stream().forEach((r) -> System.out.println(r));
- context.stop();
- }
+ context.addRoutes(new RouteBuilder() {
+
+ @Override
+ public void configure() throws Exception {
+ from("stream:in").to("direct:greetings");
+ from("direct:greetings").to("stream:out");
+ }
+ });
+
+ context.start();
+ context.getRoutes().stream().forEach((r) -> System.out.println(r));
+ context.stop();
+ }
}
diff --git a/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java b/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java
index fa3af1161..d36fff43f 100644
--- a/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java
+++ b/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java
@@ -8,10 +8,10 @@ import org.junit.Test;
*
*/
public class AppTest {
-
- @Test
- public void test() throws Exception {
- String[] args = {};
- App.main(args);
- }
+
+ @Test
+ public void test() throws Exception {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java
index 0ba34b5d4..097ea3932 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java
@@ -5,34 +5,37 @@ package com.iluwatar.model.view.controller;
* Model-View-Controller is a pattern for implementing user interfaces. It divides the application
* into three interconnected parts namely the model, the view and the controller.
*
- * The central component of MVC, the model, captures the behavior of the application in terms of its problem
- * domain, independent of the user interface. The model directly manages the data, logic and rules of the
- * application. A view can be any output representation of information, such as a chart or a diagram
- * The third part, the controller, accepts input and converts it to commands for the model or view.
+ * The central component of MVC, the model, captures the behavior of the application in terms of its
+ * problem domain, independent of the user interface. The model directly manages the data, logic and
+ * rules of the application. A view can be any output representation of information, such as a chart
+ * or a diagram The third part, the controller, accepts input and converts it to commands for the
+ * model or view.
*
- * In this example we have a giant ({@link GiantModel}) with statuses for health, fatigue and nourishment. {@link GiantView}
- * can display the giant with its current status. {@link GiantController} receives input affecting the model and
- * delegates redrawing the giant to the view.
+ * In this example we have a giant ({@link GiantModel}) with statuses for health, fatigue and
+ * nourishment. {@link GiantView} can display the giant with its current status.
+ * {@link GiantController} receives input affecting the model and delegates redrawing the giant to
+ * the view.
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
- // create model, view and controller
- GiantModel giant = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
- GiantView view = new GiantView();
- GiantController controller = new GiantController(giant, view);
- // initial display
- controller.updateView();
- // controller receives some interactions that affect the giant
- controller.setHealth(Health.WOUNDED);
- controller.setNourishment(Nourishment.HUNGRY);
- controller.setFatigue(Fatigue.TIRED);
- // redisplay
- controller.updateView();
- }
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ // create model, view and controller
+ GiantModel giant = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
+ GiantView view = new GiantView();
+ GiantController controller = new GiantController(giant, view);
+ // initial display
+ controller.updateView();
+ // controller receives some interactions that affect the giant
+ controller.setHealth(Health.WOUNDED);
+ controller.setNourishment(Nourishment.HUNGRY);
+ controller.setFatigue(Fatigue.TIRED);
+ // redisplay
+ controller.updateView();
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java
index d19df6a8c..d4a60ba93 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java
@@ -7,16 +7,16 @@ package com.iluwatar.model.view.controller;
*/
public enum Fatigue {
- ALERT("alert"), TIRED("tired"), SLEEPING("sleeping");
-
- private String title;
-
- Fatigue(String title) {
- this.title = title;
- }
+ ALERT("alert"), TIRED("tired"), SLEEPING("sleeping");
- @Override
- public String toString() {
- return title;
- }
+ private String title;
+
+ Fatigue(String title) {
+ this.title = title;
+ }
+
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java
index acda727d9..42dcaf539 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java
@@ -7,39 +7,39 @@ package com.iluwatar.model.view.controller;
*/
public class GiantController {
- private GiantModel giant;
- private GiantView view;
+ private GiantModel giant;
+ private GiantView view;
- public GiantController(GiantModel giant, GiantView view) {
- this.giant = giant;
- this.view = view;
- }
-
- public Health getHealth() {
- return giant.getHealth();
- }
+ public GiantController(GiantModel giant, GiantView view) {
+ this.giant = giant;
+ this.view = view;
+ }
- public void setHealth(Health health) {
- this.giant.setHealth(health);
- }
+ public Health getHealth() {
+ return giant.getHealth();
+ }
- public Fatigue getFatigue() {
- return giant.getFatigue();
- }
+ public void setHealth(Health health) {
+ this.giant.setHealth(health);
+ }
- public void setFatigue(Fatigue fatigue) {
- this.giant.setFatigue(fatigue);
- }
+ public Fatigue getFatigue() {
+ return giant.getFatigue();
+ }
- public Nourishment getNourishment() {
- return giant.getNourishment();
- }
+ public void setFatigue(Fatigue fatigue) {
+ this.giant.setFatigue(fatigue);
+ }
- public void setNourishment(Nourishment nourishment) {
- this.giant.setNourishment(nourishment);
- }
-
- public void updateView() {
- this.view.displayGiant(giant);
- }
+ public Nourishment getNourishment() {
+ return giant.getNourishment();
+ }
+
+ public void setNourishment(Nourishment nourishment) {
+ this.giant.setNourishment(nourishment);
+ }
+
+ public void updateView() {
+ this.view.displayGiant(giant);
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java
index 97c298768..2ecbe8b1f 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java
@@ -6,43 +6,43 @@ package com.iluwatar.model.view.controller;
*
*/
public class GiantModel {
-
- private Health health;
- private Fatigue fatigue;
- private Nourishment nourishment;
- GiantModel(Health health, Fatigue fatigue, Nourishment nourishment) {
- this.health = health;
- this.fatigue = fatigue;
- this.nourishment = nourishment;
- }
+ private Health health;
+ private Fatigue fatigue;
+ private Nourishment nourishment;
- public Health getHealth() {
- return health;
- }
+ GiantModel(Health health, Fatigue fatigue, Nourishment nourishment) {
+ this.health = health;
+ this.fatigue = fatigue;
+ this.nourishment = nourishment;
+ }
- public void setHealth(Health health) {
- this.health = health;
- }
+ public Health getHealth() {
+ return health;
+ }
- public Fatigue getFatigue() {
- return fatigue;
- }
+ public void setHealth(Health health) {
+ this.health = health;
+ }
- public void setFatigue(Fatigue fatigue) {
- this.fatigue = fatigue;
- }
+ public Fatigue getFatigue() {
+ return fatigue;
+ }
- public Nourishment getNourishment() {
- return nourishment;
- }
+ public void setFatigue(Fatigue fatigue) {
+ this.fatigue = fatigue;
+ }
- public void setNourishment(Nourishment nourishment) {
- this.nourishment = nourishment;
- }
-
- @Override
- public String toString() {
- return String.format("The giant looks %s, %s and %s.", health, fatigue, nourishment);
- }
+ public Nourishment getNourishment() {
+ return nourishment;
+ }
+
+ public void setNourishment(Nourishment nourishment) {
+ this.nourishment = nourishment;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("The giant looks %s, %s and %s.", health, fatigue, nourishment);
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java
index 1cf5e20a6..5b2c8e840 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java
@@ -7,7 +7,7 @@ package com.iluwatar.model.view.controller;
*/
public class GiantView {
- public void displayGiant(GiantModel giant) {
- System.out.println(giant);
- }
+ public void displayGiant(GiantModel giant) {
+ System.out.println(giant);
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java
index feaec81d7..9bde455dd 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java
@@ -6,17 +6,17 @@ package com.iluwatar.model.view.controller;
*
*/
public enum Health {
-
- HEALTHY("healthy"), WOUNDED("wounded"), DEAD("dead");
-
- private String title;
-
- Health(String title) {
- this.title = title;
- }
- @Override
- public String toString() {
- return title;
- }
+ HEALTHY("healthy"), WOUNDED("wounded"), DEAD("dead");
+
+ private String title;
+
+ Health(String title) {
+ this.title = title;
+ }
+
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java
index 7bab931b6..c3e043906 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java
@@ -7,16 +7,16 @@ package com.iluwatar.model.view.controller;
*/
public enum Nourishment {
- SATURATED("saturated"), HUNGRY("hungry"), STARVING("starving");
-
- private String title;
-
- Nourishment(String title) {
- this.title = title;
- }
+ SATURATED("saturated"), HUNGRY("hungry"), STARVING("starving");
- @Override
- public String toString() {
- return title;
- }
+ private String title;
+
+ Nourishment(String title) {
+ this.title = title;
+ }
+
+ @Override
+ public String toString() {
+ return title;
+ }
}
diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java
index 4bb31f6e6..7142c2979 100644
--- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java
+++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java
@@ -10,10 +10,10 @@ import com.iluwatar.model.view.controller.App;
*
*/
public class AppTest {
-
- @Test
- public void test() {
- String[] args = {};
- App.main(args);
- }
+
+ @Test
+ public void test() {
+ String[] args = {};
+ App.main(args);
+ }
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java
index ac6ccf091..2dc3f4d51 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java
@@ -2,30 +2,31 @@ package com.iluwatar.model.view.presenter;
/**
*
- * The Model-View-Presenter(MVP) architectural pattern, helps us achieve what is
- * called "The separation of concerns" principle. This is accomplished
- * by separating the application's logic (Model), GUIs (View), and finally
- * the way that the user's actions update the application's logic (Presenter).
+ * The Model-View-Presenter(MVP) architectural pattern, helps us achieve what is called
+ * "The separation of concerns" principle. This is accomplished by separating the application's
+ * logic (Model), GUIs (View), and finally the way that the user's actions update the application's
+ * logic (Presenter).
*
- * In the following example, The {@link FileLoader} class represents the app's logic,
- * the {@link FileSelectorJFrame} is the GUI and the {@link FileSelectorPresenter} is
- * responsible to respond to users' actions.
+ * In the following example, The {@link FileLoader} class represents the app's logic, the
+ * {@link FileSelectorJFrame} is the GUI and the {@link FileSelectorPresenter} is responsible to
+ * respond to users' actions.
*
- * Finally, please notice the wiring between the Presenter and the View
- * and between the Presenter and the Model.
+ * Finally, please notice the wiring between the Presenter and the View and between the Presenter
+ * and the Model.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- FileLoader loader = new FileLoader();
- FileSelectorJFrame jFrame = new FileSelectorJFrame();
- FileSelectorPresenter presenter = new FileSelectorPresenter(jFrame);
- presenter.setLoader(loader);
- presenter.start();
- }
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ FileLoader loader = new FileLoader();
+ FileSelectorJFrame jFrame = new FileSelectorJFrame();
+ FileSelectorPresenter presenter = new FileSelectorPresenter(jFrame);
+ presenter.setLoader(loader);
+ presenter.start();
+ }
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java
index 96d843f83..d04f284ac 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java
@@ -5,76 +5,76 @@ import java.io.File;
import java.io.FileReader;
/**
- * Every instance of this class represents the Model component in the
- * Model-View-Presenter architectural pattern.
+ * Every instance of this class represents the Model component in the Model-View-Presenter
+ * architectural pattern.
*
* It is responsible for reading and loading the contents of a given file.
*/
public class FileLoader {
- /**
- * Indicates if the file is loaded or not.
- */
- private boolean loaded = false;
+ /**
+ * Indicates if the file is loaded or not.
+ */
+ private boolean loaded = false;
- /**
- * The name of the file that we want to load.
- */
- private String fileName;
+ /**
+ * The name of the file that we want to load.
+ */
+ private String fileName;
- /**
- * Loads the data of the file specified.
- */
- public String loadData() {
- try {
- BufferedReader br = new BufferedReader(new FileReader(new File(
- this.fileName)));
- StringBuilder sb = new StringBuilder();
- String line;
+ /**
+ * Loads the data of the file specified.
+ */
+ public String loadData() {
+ try {
+ BufferedReader br = new BufferedReader(new FileReader(new File(this.fileName)));
+ StringBuilder sb = new StringBuilder();
+ String line;
- while ((line = br.readLine()) != null) {
- sb.append(line).append('\n');
- }
+ while ((line = br.readLine()) != null) {
+ sb.append(line).append('\n');
+ }
- this.loaded = true;
- br.close();
+ this.loaded = true;
+ br.close();
- return sb.toString();
- }
+ return sb.toString();
+ }
- catch (Exception e) {
- e.printStackTrace();
- }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
- return null;
- }
+ return null;
+ }
- /**
- * Sets the path of the file to be loaded, to the given value.
- * @param fileName The path of the file to be loaded.
- */
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
+ /**
+ * Sets the path of the file to be loaded, to the given value.
+ *
+ * @param fileName The path of the file to be loaded.
+ */
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
- /**
- * @return fileName The path of the file to be loaded.
- */
- public String getFileName() {
- return this.fileName;
- }
+ /**
+ * @return fileName The path of the file to be loaded.
+ */
+ public String getFileName() {
+ return this.fileName;
+ }
- /**
- * @return True, if the file given exists, false otherwise.
- */
- public boolean fileExists() {
- return new File(this.fileName).exists();
- }
+ /**
+ * @return True, if the file given exists, false otherwise.
+ */
+ public boolean fileExists() {
+ return new File(this.fileName).exists();
+ }
- /**
- * @return True, if the file is loaded, false otherwise.
- */
- public boolean isLoaded() {
- return this.loaded;
- }
+ /**
+ * @return True, if the file is loaded, false otherwise.
+ */
+ public boolean isLoaded() {
+ return this.loaded;
+ }
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java
index f4d24f59f..02cb2703a 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java
@@ -14,187 +14,185 @@ import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
- * This class is the GUI implementation of the View component in the
- * Model-View-Presenter pattern.
+ * This class is the GUI implementation of the View component in the Model-View-Presenter pattern.
*/
-public class FileSelectorJFrame extends JFrame implements FileSelectorView,
- ActionListener {
+public class FileSelectorJFrame extends JFrame implements FileSelectorView, ActionListener {
- /**
- * Default serial version ID.
- */
- private static final long serialVersionUID = 1L;
+ /**
+ * Default serial version ID.
+ */
+ private static final long serialVersionUID = 1L;
- /**
- * The "OK" button for loading the file.
- */
- private JButton OK;
+ /**
+ * The "OK" button for loading the file.
+ */
+ private JButton OK;
- /**
- * The cancel button.
- */
- private JButton cancel;
+ /**
+ * The cancel button.
+ */
+ private JButton cancel;
- /**
- * The information label.
- */
- private JLabel info;
+ /**
+ * The information label.
+ */
+ private JLabel info;
- /**
- * The contents label.
- */
- private JLabel contents;
+ /**
+ * The contents label.
+ */
+ private JLabel contents;
- /**
- * The text field for giving the name of the file that we want to open.
- */
- private JTextField input;
+ /**
+ * The text field for giving the name of the file that we want to open.
+ */
+ private JTextField input;
- /**
- * A text area that will keep the contents of the file opened.
- */
- private JTextArea area;
+ /**
+ * A text area that will keep the contents of the file opened.
+ */
+ private JTextArea area;
- /**
- * The panel that will hold our widgets.
- */
- private JPanel panel;
+ /**
+ * The panel that will hold our widgets.
+ */
+ private JPanel panel;
- /**
- * The Presenter component that the frame will interact with
- */
- private FileSelectorPresenter presenter;
+ /**
+ * The Presenter component that the frame will interact with
+ */
+ private FileSelectorPresenter presenter;
- /**
- * The name of the file that we want to read it's contents.
- */
- private String fileName;
+ /**
+ * The name of the file that we want to read it's contents.
+ */
+ private String fileName;
- /**
- * Constructor.
- */
- public FileSelectorJFrame() {
- super("File Loader");
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- this.setLayout(null);
- this.setBounds(100, 100, 500, 200);
+ /**
+ * Constructor.
+ */
+ public FileSelectorJFrame() {
+ super("File Loader");
+ this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ this.setLayout(null);
+ this.setBounds(100, 100, 500, 200);
- /*
- * Add the panel.
- */
- this.panel = new JPanel();
- panel.setLayout(null);
- this.add(panel);
- panel.setBounds(0, 0, 500, 200);
- panel.setBackground(Color.LIGHT_GRAY);
+ /*
+ * Add the panel.
+ */
+ this.panel = new JPanel();
+ panel.setLayout(null);
+ this.add(panel);
+ panel.setBounds(0, 0, 500, 200);
+ panel.setBackground(Color.LIGHT_GRAY);
- /*
- * Add the info label.
- */
- this.info = new JLabel("File Name :");
- this.panel.add(info);
- info.setBounds(30, 10, 100, 30);
+ /*
+ * Add the info label.
+ */
+ this.info = new JLabel("File Name :");
+ this.panel.add(info);
+ info.setBounds(30, 10, 100, 30);
- /*
- * Add the contents label.
- */
- this.contents = new JLabel("File contents :");
- this.panel.add(contents);
- this.contents.setBounds(30, 100, 120, 30);
+ /*
+ * Add the contents label.
+ */
+ this.contents = new JLabel("File contents :");
+ this.panel.add(contents);
+ this.contents.setBounds(30, 100, 120, 30);
- /*
- * Add the text field.
- */
- this.input = new JTextField(100);
- this.panel.add(input);
- this.input.setBounds(150, 15, 200, 20);
+ /*
+ * Add the text field.
+ */
+ this.input = new JTextField(100);
+ this.panel.add(input);
+ this.input.setBounds(150, 15, 200, 20);
- /*
- * Add the text area.
- */
- this.area = new JTextArea(100, 100);
- JScrollPane pane = new JScrollPane(area);
- pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
- pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
- this.panel.add(pane);
- this.area.setEditable(false);
- pane.setBounds(150, 100, 250, 80);
+ /*
+ * Add the text area.
+ */
+ this.area = new JTextArea(100, 100);
+ JScrollPane pane = new JScrollPane(area);
+ pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
+ pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
+ this.panel.add(pane);
+ this.area.setEditable(false);
+ pane.setBounds(150, 100, 250, 80);
- /*
- * Add the OK button.
- */
- this.OK = new JButton("OK");
- this.panel.add(OK);
- this.OK.setBounds(250, 50, 100, 25);
- this.OK.addActionListener(this);
+ /*
+ * Add the OK button.
+ */
+ this.OK = new JButton("OK");
+ this.panel.add(OK);
+ this.OK.setBounds(250, 50, 100, 25);
+ this.OK.addActionListener(this);
- /*
- * Add the cancel button.
- */
- this.cancel = new JButton("Cancel");
- this.panel.add(this.cancel);
- this.cancel.setBounds(380, 50, 100, 25);
- this.cancel.addActionListener(this);
+ /*
+ * Add the cancel button.
+ */
+ this.cancel = new JButton("Cancel");
+ this.panel.add(this.cancel);
+ this.cancel.setBounds(380, 50, 100, 25);
+ this.cancel.addActionListener(this);
- this.presenter = null;
- this.fileName = null;
- }
+ this.presenter = null;
+ this.fileName = null;
+ }
- @Override
- public void actionPerformed(ActionEvent e) {
- if (e.getSource() == this.OK) {
- this.fileName = this.input.getText();
- presenter.fileNameChanged();
- presenter.confirmed();
- }
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ if (e.getSource() == this.OK) {
+ this.fileName = this.input.getText();
+ presenter.fileNameChanged();
+ presenter.confirmed();
+ }
- else if (e.getSource() == this.cancel) {
- presenter.cancelled();
- }
- }
+ else if (e.getSource() == this.cancel) {
+ presenter.cancelled();
+ }
+ }
- @Override
- public void open() {
- this.setVisible(true);
- }
+ @Override
+ public void open() {
+ this.setVisible(true);
+ }
- @Override
- public void close() {
- this.dispose();
- }
+ @Override
+ public void close() {
+ this.dispose();
+ }
- @Override
- public boolean isOpened() {
- return this.isVisible();
- }
+ @Override
+ public boolean isOpened() {
+ return this.isVisible();
+ }
- @Override
- public void setPresenter(FileSelectorPresenter presenter) {
- this.presenter = presenter;
- }
+ @Override
+ public void setPresenter(FileSelectorPresenter presenter) {
+ this.presenter = presenter;
+ }
- @Override
- public FileSelectorPresenter getPresenter() {
- return this.presenter;
- }
+ @Override
+ public FileSelectorPresenter getPresenter() {
+ return this.presenter;
+ }
- @Override
- public void setFileName(String name) {
- this.fileName = name;
- }
+ @Override
+ public void setFileName(String name) {
+ this.fileName = name;
+ }
- @Override
- public String getFileName() {
- return this.fileName;
- }
+ @Override
+ public String getFileName() {
+ return this.fileName;
+ }
- @Override
- public void showMessage(String message) {
- JOptionPane.showMessageDialog(null, message);
- }
+ @Override
+ public void showMessage(String message) {
+ JOptionPane.showMessageDialog(null, message);
+ }
- @Override
- public void displayData(String data) {
- this.area.setText(data);
- }
+ @Override
+ public void displayData(String data) {
+ this.area.setText(data);
+ }
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java
index 7119d60bf..133d8555d 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java
@@ -1,75 +1,76 @@
package com.iluwatar.model.view.presenter;
/**
- * Every instance of this class represents the Presenter component in the
- * Model-View-Presenter architectural pattern.
+ * Every instance of this class represents the Presenter component in the Model-View-Presenter
+ * architectural pattern.
*
- * It is responsible for reacting to the user's actions and update the View
- * component.
+ * It is responsible for reacting to the user's actions and update the View component.
*/
public class FileSelectorPresenter {
- /**
- * The View component that the presenter interacts with.
- */
- private FileSelectorView view;
+ /**
+ * The View component that the presenter interacts with.
+ */
+ private FileSelectorView view;
- /**
- * The Model component that the presenter interacts with.
- */
- private FileLoader loader;
+ /**
+ * The Model component that the presenter interacts with.
+ */
+ private FileLoader loader;
- /**
- * Constructor
- * @param view The view component that the presenter will interact with.
- */
- public FileSelectorPresenter(FileSelectorView view) {
- this.view = view;
- }
+ /**
+ * Constructor
+ *
+ * @param view The view component that the presenter will interact with.
+ */
+ public FileSelectorPresenter(FileSelectorView view) {
+ this.view = view;
+ }
- /**
- * Sets the {@link FileLoader} object, to the value given as parameter.
- * @param loader The new {@link FileLoader} object(the Model component).
- */
- public void setLoader(FileLoader loader) {
- this.loader = loader;
- }
+ /**
+ * Sets the {@link FileLoader} object, to the value given as parameter.
+ *
+ * @param loader The new {@link FileLoader} object(the Model component).
+ */
+ public void setLoader(FileLoader loader) {
+ this.loader = loader;
+ }
- /**
- * Starts the presenter.
- */
- public void start() {
- view.setPresenter(this);
- view.open();
- }
+ /**
+ * Starts the presenter.
+ */
+ public void start() {
+ view.setPresenter(this);
+ view.open();
+ }
- /**
- * An "event" that fires when the name of the file to be loaded changes.
- */
- public void fileNameChanged() {
- loader.setFileName(view.getFileName());
- }
+ /**
+ * An "event" that fires when the name of the file to be loaded changes.
+ */
+ public void fileNameChanged() {
+ loader.setFileName(view.getFileName());
+ }
- public void confirmed() {
- if (loader.getFileName() == null || loader.getFileName().equals("")) {
- view.showMessage("Please give the name of the file first!");
- return;
- }
+ public void confirmed() {
+ if (loader.getFileName() == null || loader.getFileName().equals("")) {
+ view.showMessage("Please give the name of the file first!");
+ return;
+ }
- if (loader.fileExists()) {
- String data = loader.loadData();
- view.displayData(data);
- }
+ if (loader.fileExists()) {
+ String data = loader.loadData();
+ view.displayData(data);
+ }
- else {
- view.showMessage("The file specified does not exist.");
- }
- }
+ else {
+ view.showMessage("The file specified does not exist.");
+ }
+ }
- /**
- * Cancels the file loading process.
- */
- public void cancelled() {
- view.close();
- }
+ /**
+ * Cancels the file loading process.
+ */
+ public void cancelled() {
+ view.close();
+ }
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java
index d0cec4c40..ac338ef22 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java
@@ -1,109 +1,109 @@
package com.iluwatar.model.view.presenter;
/**
- * Every instance of this class represents the Stub component in the
- * Model-View-Presenter architectural pattern.
+ * Every instance of this class represents the Stub component in the Model-View-Presenter
+ * architectural pattern.
*
- * The stub implements the View interface and it is useful when we want the test
- * the reaction to user events, such as mouse clicks.
+ * The stub implements the View interface and it is useful when we want the test the reaction to
+ * user events, such as mouse clicks.
*
- * Since we can not test the GUI directly, the MVP pattern provides this
- * functionality through the View's dummy implementation, the Stub.
+ * Since we can not test the GUI directly, the MVP pattern provides this functionality through the
+ * View's dummy implementation, the Stub.
*/
public class FileSelectorStub implements FileSelectorView {
- /**
- * Indicates whether or not the view is opened.
- */
- private boolean opened;
+ /**
+ * Indicates whether or not the view is opened.
+ */
+ private boolean opened;
- /**
- * The presenter Component.
- */
- private FileSelectorPresenter presenter;
+ /**
+ * The presenter Component.
+ */
+ private FileSelectorPresenter presenter;
- /**
- * The current name of the file.
- */
- private String name;
+ /**
+ * The current name of the file.
+ */
+ private String name;
- /**
- * Indicates the number of messages that were "displayed" to the user.
- */
- private int numOfMessageSent;
+ /**
+ * Indicates the number of messages that were "displayed" to the user.
+ */
+ private int numOfMessageSent;
- /**
- * Indicates if the data of the file where displayed or not.
- */
- private boolean dataDisplayed;
+ /**
+ * Indicates if the data of the file where displayed or not.
+ */
+ private boolean dataDisplayed;
- /**
- * Constructor
- */
- public FileSelectorStub() {
- this.opened = false;
- this.presenter = null;
- this.name = "";
- this.numOfMessageSent = 0;
- this.dataDisplayed = false;
- }
+ /**
+ * Constructor
+ */
+ public FileSelectorStub() {
+ this.opened = false;
+ this.presenter = null;
+ this.name = "";
+ this.numOfMessageSent = 0;
+ this.dataDisplayed = false;
+ }
- @Override
- public void open() {
- this.opened = true;
- }
+ @Override
+ public void open() {
+ this.opened = true;
+ }
- @Override
- public void setPresenter(FileSelectorPresenter presenter) {
- this.presenter = presenter;
- }
+ @Override
+ public void setPresenter(FileSelectorPresenter presenter) {
+ this.presenter = presenter;
+ }
- @Override
- public boolean isOpened() {
- return this.opened;
- }
+ @Override
+ public boolean isOpened() {
+ return this.opened;
+ }
- @Override
- public FileSelectorPresenter getPresenter() {
- return this.presenter;
- }
+ @Override
+ public FileSelectorPresenter getPresenter() {
+ return this.presenter;
+ }
- @Override
- public String getFileName() {
- return this.name;
- }
+ @Override
+ public String getFileName() {
+ return this.name;
+ }
- @Override
- public void setFileName(String name) {
- this.name = name;
- }
+ @Override
+ public void setFileName(String name) {
+ this.name = name;
+ }
- @Override
- public void showMessage(String message) {
- this.numOfMessageSent++;
- }
+ @Override
+ public void showMessage(String message) {
+ this.numOfMessageSent++;
+ }
- @Override
- public void close() {
- this.opened = false;
- }
+ @Override
+ public void close() {
+ this.opened = false;
+ }
- @Override
- public void displayData(String data) {
- this.dataDisplayed = true;
- }
+ @Override
+ public void displayData(String data) {
+ this.dataDisplayed = true;
+ }
- /**
- * Returns the number of messages that were displayed to the user.
- */
- public int getMessagesSent() {
- return this.numOfMessageSent;
- }
+ /**
+ * Returns the number of messages that were displayed to the user.
+ */
+ public int getMessagesSent() {
+ return this.numOfMessageSent;
+ }
- /**
- * @return True if the data where displayed, false otherwise.
- */
- public boolean dataDisplayed() {
- return this.dataDisplayed;
- }
+ /**
+ * @return True if the data where displayed, false otherwise.
+ */
+ public boolean dataDisplayed() {
+ return this.dataDisplayed;
+ }
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java
index 8cd265f9b..80cfadd28 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java
@@ -1,57 +1,61 @@
package com.iluwatar.model.view.presenter;
/**
- * This interface represents the View component in the Model-View-Presenter
- * pattern. It can be implemented by either the GUI components, or by the Stub.
+ * This interface represents the View component in the Model-View-Presenter pattern. It can be
+ * implemented by either the GUI components, or by the Stub.
*/
public interface FileSelectorView {
- /**
- * Opens the view.
- */
- public void open();
+ /**
+ * Opens the view.
+ */
+ public void open();
- /**
- * Closes the view.
- */
- public void close();
+ /**
+ * Closes the view.
+ */
+ public void close();
- /**
- * @return True, if the view is opened, false otherwise.
- */
- public boolean isOpened();
+ /**
+ * @return True, if the view is opened, false otherwise.
+ */
+ public boolean isOpened();
- /**
- * Sets the presenter component, to the one given as parameter.
- * @param presenter The new presenter component.
- */
- public void setPresenter(FileSelectorPresenter presenter);
+ /**
+ * Sets the presenter component, to the one given as parameter.
+ *
+ * @param presenter The new presenter component.
+ */
+ public void setPresenter(FileSelectorPresenter presenter);
- /**
- * @return The presenter Component.
- */
- public FileSelectorPresenter getPresenter();
+ /**
+ * @return The presenter Component.
+ */
+ public FileSelectorPresenter getPresenter();
- /**
- * Sets the file's name, to the value given as parameter.
- * @param name The new name of the file.
- */
- public void setFileName(String name);
+ /**
+ * Sets the file's name, to the value given as parameter.
+ *
+ * @param name The new name of the file.
+ */
+ public void setFileName(String name);
- /**
- * @return The name of the file.
- */
- public String getFileName();
+ /**
+ * @return The name of the file.
+ */
+ public String getFileName();
- /**
- * Displays a message to the users.
- * @param message The message to be displayed.
- */
- public void showMessage(String message);
+ /**
+ * Displays a message to the users.
+ *
+ * @param message The message to be displayed.
+ */
+ public void showMessage(String message);
- /**
- * Displays the data to the view.
- * @param data The data to be written.
- */
- public void displayData(String data);
+ /**
+ * Displays the data to the view.
+ *
+ * @param data The data to be written.
+ */
+ public void displayData(String data);
}
diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java
index 119448e9c..dfdcba31b 100644
--- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java
+++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java
@@ -10,116 +10,115 @@ import com.iluwatar.model.view.presenter.FileSelectorPresenter;
import com.iluwatar.model.view.presenter.FileSelectorStub;
/**
- * This test case is responsible for testing our application by taking advantage
- * of the Model-View-Controller architectural pattern.
+ * This test case is responsible for testing our application by taking advantage of the
+ * Model-View-Controller architectural pattern.
*/
public class FileSelectorPresenterTest {
- /**
- * The Presenter component.
- */
- private FileSelectorPresenter presenter;
+ /**
+ * The Presenter component.
+ */
+ private FileSelectorPresenter presenter;
- /**
- * The View component, implemented this time as a Stub!!!
- */
- private FileSelectorStub stub;
+ /**
+ * The View component, implemented this time as a Stub!!!
+ */
+ private FileSelectorStub stub;
- /**
- * The Model component.
- */
- private FileLoader loader;
+ /**
+ * The Model component.
+ */
+ private FileLoader loader;
- /**
- * Initializes the components of the test case.
- */
- @Before
- public void setUp() {
- this.stub = new FileSelectorStub();
- this.loader = new FileLoader();
- presenter = new FileSelectorPresenter(this.stub);
- presenter.setLoader(loader);
- }
+ /**
+ * Initializes the components of the test case.
+ */
+ @Before
+ public void setUp() {
+ this.stub = new FileSelectorStub();
+ this.loader = new FileLoader();
+ presenter = new FileSelectorPresenter(this.stub);
+ presenter.setLoader(loader);
+ }
- /**
- * Tests if the Presenter was successfully connected with the View.
- */
- @Test
- public void wiring() {
- presenter.start();
+ /**
+ * Tests if the Presenter was successfully connected with the View.
+ */
+ @Test
+ public void wiring() {
+ presenter.start();
- assertNotNull(stub.getPresenter());
- assertTrue(stub.isOpened());
- }
+ assertNotNull(stub.getPresenter());
+ assertTrue(stub.isOpened());
+ }
- /**
- * Tests if the name of the file changes.
- */
- @Test
- public void updateFileNameToLoader() {
- String EXPECTED_FILE = "Stamatis";
- stub.setFileName(EXPECTED_FILE);
+ /**
+ * Tests if the name of the file changes.
+ */
+ @Test
+ public void updateFileNameToLoader() {
+ String EXPECTED_FILE = "Stamatis";
+ stub.setFileName(EXPECTED_FILE);
- presenter.start();
- presenter.fileNameChanged();
+ presenter.start();
+ presenter.fileNameChanged();
- assertEquals(EXPECTED_FILE, loader.getFileName());
- }
+ assertEquals(EXPECTED_FILE, loader.getFileName());
+ }
- /**
- * Tests if we receive a confirmation when we attempt to open a file that
- * it's name is null or an empty string.
- */
- @Test
- public void fileConfirmationWhenNameIsNull() {
- stub.setFileName(null);
+ /**
+ * Tests if we receive a confirmation when we attempt to open a file that it's name is null or an
+ * empty string.
+ */
+ @Test
+ public void fileConfirmationWhenNameIsNull() {
+ stub.setFileName(null);
- presenter.start();
- presenter.fileNameChanged();
- presenter.confirmed();
+ presenter.start();
+ presenter.fileNameChanged();
+ presenter.confirmed();
- assertFalse(loader.isLoaded());
- assertEquals(1, stub.getMessagesSent());
- }
+ assertFalse(loader.isLoaded());
+ assertEquals(1, stub.getMessagesSent());
+ }
- /**
- * Tests if we receive a confirmation when we attempt to open a file that it
- * doesn't exist.
- */
- @Test
- public void fileConfirmationWhenFileDoesNotExist() {
- stub.setFileName("RandomName.txt");
+ /**
+ * Tests if we receive a confirmation when we attempt to open a file that it doesn't exist.
+ */
+ @Test
+ public void fileConfirmationWhenFileDoesNotExist() {
+ stub.setFileName("RandomName.txt");
- presenter.start();
- presenter.fileNameChanged();
- presenter.confirmed();
+ presenter.start();
+ presenter.fileNameChanged();
+ presenter.confirmed();
- assertFalse(loader.isLoaded());
- assertEquals(1, stub.getMessagesSent());
- }
+ assertFalse(loader.isLoaded());
+ assertEquals(1, stub.getMessagesSent());
+ }
- /**
- * Tests if we can open the file, when it exists.
- */
- @Test
- public void fileConfirmationWhenFileExists() {
- stub.setFileName("etc/data/test.txt");
- presenter.start();
- presenter.fileNameChanged();
- presenter.confirmed();
+ /**
+ * Tests if we can open the file, when it exists.
+ */
+ @Test
+ public void fileConfirmationWhenFileExists() {
+ stub.setFileName("etc/data/test.txt");
+ presenter.start();
+ presenter.fileNameChanged();
+ presenter.confirmed();
- assertTrue(loader.isLoaded());
- assertTrue(stub.dataDisplayed());
- }
+ assertTrue(loader.isLoaded());
+ assertTrue(stub.dataDisplayed());
+ }
- /**
- * Tests if the view closes after cancellation.
- */
- @Test
- public void cancellation() {
- presenter.start();
- presenter.cancelled();
+ /**
+ * Tests if the view closes after cancellation.
+ */
+ @Test
+ public void cancellation() {
+ presenter.start();
+ presenter.cancelled();
- assertFalse(stub.isOpened());
- }
+ assertFalse(stub.isOpened());
+ }
}
diff --git a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
index 7bc0043e8..b81e44251 100644
--- a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
+++ b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
@@ -46,7 +46,7 @@ public class LoadBalancer {
Server server = servers.get(lastServedId++);
server.serve(request);
}
-
+
}
diff --git a/monostate/src/main/java/com/iluwatar/monostate/Request.java b/monostate/src/main/java/com/iluwatar/monostate/Request.java
index ee1f31d85..b18ba8ff2 100644
--- a/monostate/src/main/java/com/iluwatar/monostate/Request.java
+++ b/monostate/src/main/java/com/iluwatar/monostate/Request.java
@@ -2,7 +2,7 @@ package com.iluwatar.monostate;
/**
*
- * The Request class. A {@link Server} can handle an instance of a Request.
+ * The Request class. A {@link Server} can handle an instance of a Request.
*
*/
diff --git a/monostate/src/main/java/com/iluwatar/monostate/Server.java b/monostate/src/main/java/com/iluwatar/monostate/Server.java
index ce4e0222d..f48f4ad0f 100644
--- a/monostate/src/main/java/com/iluwatar/monostate/Server.java
+++ b/monostate/src/main/java/com/iluwatar/monostate/Server.java
@@ -2,8 +2,8 @@ package com.iluwatar.monostate;
/**
*
- * The Server class. Each Server sits behind a LoadBalancer which delegates the call to the
- * servers in a simplistic Round Robin fashion.
+ * The Server class. Each Server sits behind a LoadBalancer which delegates the call to the servers
+ * in a simplistic Round Robin fashion.
*
*/
public class Server {
@@ -26,6 +26,7 @@ public class Server {
}
public final void serve(Request request) {
- System.out.println("Server ID " + id + " associated to host : " + getHost() + " and Port " + getPort() +" Processed request with value " + request.value);
+ System.out.println("Server ID " + id + " associated to host : " + getHost() + " and Port "
+ + getPort() + " Processed request with value " + request.value);
}
}
diff --git a/monostate/src/test/java/com/iluwatar/monostate/AppTest.java b/monostate/src/test/java/com/iluwatar/monostate/AppTest.java
index c5f1f7e92..c502dd14a 100644
--- a/monostate/src/test/java/com/iluwatar/monostate/AppTest.java
+++ b/monostate/src/test/java/com/iluwatar/monostate/AppTest.java
@@ -15,7 +15,7 @@ public class AppTest {
// Both Should have the same LastServedId
Assert.assertTrue(balancer.getLastServedId() == balancer2.getLastServedId());
}
-
+
@Test
public void testMain() {
String[] args = {};
diff --git a/multiton/src/main/java/com/iluwatar/multiton/App.java b/multiton/src/main/java/com/iluwatar/multiton/App.java
index 9f2c5da78..273087310 100644
--- a/multiton/src/main/java/com/iluwatar/multiton/App.java
+++ b/multiton/src/main/java/com/iluwatar/multiton/App.java
@@ -2,31 +2,31 @@ package com.iluwatar.multiton;
/**
*
- * Whereas Singleton design pattern introduces single globally
- * accessible object the Multiton pattern defines many globally
- * accessible objects. The client asks for the correct instance
- * from the Multiton by passing an enumeration as parameter.
+ * Whereas Singleton design pattern introduces single globally accessible object the Multiton
+ * pattern defines many globally accessible objects. The client asks for the correct instance from
+ * the Multiton by passing an enumeration as parameter.
*
- * In this example {@link Nazgul} is the Multiton and we can ask single
- * {@link Nazgul} from it using {@link NazgulName}. The {@link Nazgul}s are statically
- * initialized and stored in concurrent hash map.
+ * In this example {@link Nazgul} is the Multiton and we can ask single {@link Nazgul} from it using
+ * {@link NazgulName}. The {@link Nazgul}s are statically initialized and stored in concurrent hash
+ * map.
*
*/
public class App {
-
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main( String[] args ) {
- System.out.println("KHAMUL=" + Nazgul.getInstance(NazgulName.KHAMUL));
- System.out.println("MURAZOR=" + Nazgul.getInstance(NazgulName.MURAZOR));
- System.out.println("DWAR=" + Nazgul.getInstance(NazgulName.DWAR));
- System.out.println("JI_INDUR=" + Nazgul.getInstance(NazgulName.JI_INDUR));
- System.out.println("AKHORAHIL=" + Nazgul.getInstance(NazgulName.AKHORAHIL));
- System.out.println("HOARMURATH=" + Nazgul.getInstance(NazgulName.HOARMURATH));
- System.out.println("ADUNAPHEL=" + Nazgul.getInstance(NazgulName.ADUNAPHEL));
- System.out.println("REN=" + Nazgul.getInstance(NazgulName.REN));
- System.out.println("UVATHA=" + Nazgul.getInstance(NazgulName.UVATHA));
- }
+
+ /**
+ * Program entry point
+ *
+ * @param args command line args
+ */
+ public static void main(String[] args) {
+ System.out.println("KHAMUL=" + Nazgul.getInstance(NazgulName.KHAMUL));
+ System.out.println("MURAZOR=" + Nazgul.getInstance(NazgulName.MURAZOR));
+ System.out.println("DWAR=" + Nazgul.getInstance(NazgulName.DWAR));
+ System.out.println("JI_INDUR=" + Nazgul.getInstance(NazgulName.JI_INDUR));
+ System.out.println("AKHORAHIL=" + Nazgul.getInstance(NazgulName.AKHORAHIL));
+ System.out.println("HOARMURATH=" + Nazgul.getInstance(NazgulName.HOARMURATH));
+ System.out.println("ADUNAPHEL=" + Nazgul.getInstance(NazgulName.ADUNAPHEL));
+ System.out.println("REN=" + Nazgul.getInstance(NazgulName.REN));
+ System.out.println("UVATHA=" + Nazgul.getInstance(NazgulName.UVATHA));
+ }
}
diff --git a/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java b/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java
index 833923f75..f6f5ce84d 100644
--- a/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java
+++ b/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java
@@ -5,38 +5,37 @@ import java.util.concurrent.ConcurrentHashMap;
/**
*
- * Nazgul is a Multiton class. Nazgul instances can be queried
- * using {@link #getInstance} method.
+ * Nazgul is a Multiton class. Nazgul instances can be queried using {@link #getInstance} method.
*
*/
public class Nazgul {
- private static Maptrue
if execution is completed or failed
- */
- boolean isCompleted();
+ /**
+ * Status of the async task execution.
+ *
+ * @return true
if execution is completed or failed
+ */
+ boolean isCompleted();
- /**
- * Gets the value of completed async task.
- *
- * @return evaluated value or throws ExecutionException if execution has failed
- * @throws ExecutionException if execution has failed, containing the root cause
- * @throws IllegalStateException if execution is not completed
- */
- T getValue() throws ExecutionException;
+ /**
+ * Gets the value of completed async task.
+ *
+ * @return evaluated value or throws ExecutionException if execution has failed
+ * @throws ExecutionException if execution has failed, containing the root cause
+ * @throws IllegalStateException if execution is not completed
+ */
+ T getValue() throws ExecutionException;
- /**
- * Blocks the current thread until the async task is completed.
- *
- * @throws InterruptedException if the execution is interrupted
- */
- void await() throws InterruptedException;
+ /**
+ * Blocks the current thread until the async task is completed.
+ *
+ * @throws InterruptedException if the execution is interrupted
+ */
+ void await() throws InterruptedException;
}
diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java
index a3ed51af3..300934562 100644
--- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java
+++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java
@@ -12,116 +12,117 @@ import java.util.concurrent.atomic.AtomicInteger;
*/
public class ThreadAsyncExecutor implements AsyncExecutor {
- /** Index for thread naming */
- private final AtomicInteger idx = new AtomicInteger(0);
+ /** Index for thread naming */
+ private final AtomicInteger idx = new AtomicInteger(0);
- @Override
- public
- * A concurrent system have a mixture of short duration, mid duration and long duration tasks.
- * Mid or long duration tasks should be performed asynchronously to meet quality of service
+ * PROBLEM
+ * A concurrent system have a mixture of short duration, mid duration and long duration tasks. Mid
+ * or long duration tasks should be performed asynchronously to meet quality of service
* requirements.
- *
- *
- * The intent of this pattern is to separate the the synchronous and asynchronous processing
- * in the concurrent application by introducing two intercommunicating layers - one for sync
- * and one for async. This simplifies the programming without unduly affecting the performance.
- *
+ *
*
+ * INTENT
+ * The intent of this pattern is to separate the the synchronous and asynchronous processing in the
+ * concurrent application by introducing two intercommunicating layers - one for sync and one for
+ * async. This simplifies the programming without unduly affecting the performance.
+ *
+ *
*
*
- *
+ *
- * The main method creates an asynchronous service which does not block the main thread while
- * the task is being performed. The main thread continues its work which is similar to Async Method
- * Invocation pattern. The difference between them is that there is a queuing layer between Asynchronous
- * layer and synchronous layer, which allows for different communication patterns between both layers.
- * Such as Priority Queue can be used as queuing layer to prioritize the way tasks are executed.
- * Our implementation is just one simple way of implementing this pattern, there are many variants possible
- * as described in its applications.
+ * IMPLEMENTATION
+ * The main method creates an asynchronous service which does not block the main thread while the
+ * task is being performed. The main thread continues its work which is similar to Async Method
+ * Invocation pattern. The difference between them is that there is a queuing layer between
+ * Asynchronous layer and synchronous layer, which allows for different communication patterns
+ * between both layers. Such as Priority Queue can be used as queuing layer to prioritize the way
+ * tasks are executed. Our implementation is just one simple way of implementing this pattern, there
+ * are many variants possible as described in its applications.
*
*/
public class App {
- /**
- * Program entry point
- * @param args command line args
- */
- public static void main(String[] args) {
- AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>());
- /*
- * A new task to calculate sum is received but as this is main thread, it should not block.
- * So it passes it to the asynchronous task layer to compute and proceeds with handling other
- * incoming requests. This is particularly useful when main thread is waiting on Socket to receive
- * new incoming requests and does not wait for particular request to be completed before responding
- * to new request.
- */
- service.execute(new ArithmeticSumTask(1000));
-
- /* New task received, lets pass that to async layer for computation. So both requests will be
- * executed in parallel.
- */
- service.execute(new ArithmeticSumTask(500));
- service.execute(new ArithmeticSumTask(2000));
- service.execute(new ArithmeticSumTask(1));
- }
-
- /**
- *
- * ArithmeticSumTask
- *
- */
- static class ArithmeticSumTask implements AsyncTaskCakeDao
, CakeToppingDao
and
- * CakeLayerDao
. The repositories can be used for CRUD operations on cakes, cake toppings
- * and cake layers respectively.
+ * The data access layer is formed of Spring Data repositories CakeDao
,
+ * CakeToppingDao
and CakeLayerDao
. The repositories can be used for CRUD
+ * operations on cakes, cake toppings and cake layers respectively.
* CakeBakingService
offers
- * methods to retrieve available cake toppings and cake layers and baked cakes. Also the
+ * The business layer is built on top of the data access layer. CakeBakingService
+ * offers methods to retrieve available cake toppings and cake layers and baked cakes. Also the
* service is used to create new cakes out of cake toppings and cake layers.
* CakeInfo
, CakeToppingInfo
, CakeLayerInfo
)
- * to translate data between layers. In other words, CakeBakingService
cannot
- * return entities (Cake
, CakeTopping
, CakeLayer
)
- * directly since these reside on data access layer but instead translates these into business
- * layer DTOs (CakeInfo
, CakeToppingInfo
, CakeLayerInfo
)
- * and returns them instead. This way the presentation layer does not have any knowledge of
- * other layers than the business layer and thus is not affected by changes to them.
+ * We have applied so called strict layering which means that the layers can only access the classes
+ * directly beneath them. This leads the solution to create an additional set of DTOs (
+ * CakeInfo
, CakeToppingInfo
, CakeLayerInfo
) to translate
+ * data between layers. In other words, CakeBakingService
cannot return entities (
+ * Cake
, CakeTopping
, CakeLayer
) directly since these reside
+ * on data access layer but instead translates these into business layer DTOs (CakeInfo
, CakeToppingInfo
, CakeLayerInfo
) and returns them instead. This way
+ * the presentation layer does not have any knowledge of other layers than the business layer and
+ * thus is not affected by changes to them.
*
* @see Cake
* @see CakeTopping
@@ -45,52 +44,55 @@ import java.util.Arrays;
*/
public class App {
- private static CakeBakingService cakeBakingService = new CakeBakingServiceImpl();
-
- /**
- * Application entry point
- * @param args Command line parameters
- */
- public static void main(String[] args) {
-
- // initialize example data
- initializeData(cakeBakingService);
-
- // create view and render it
- CakeViewImpl cakeView = new CakeViewImpl(cakeBakingService);
- cakeView.render();
- }
-
- /**
- * Initializes the example data
- * @param cakeBakingService
- */
- private static void initializeData(CakeBakingService cakeBakingService) {
- cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200));
- cakeBakingService.saveNewLayer(new CakeLayerInfo("banana", 900));
- cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950));
- cakeBakingService.saveNewLayer(new CakeLayerInfo("lemon", 950));
- cakeBakingService.saveNewLayer(new CakeLayerInfo("vanilla", 950));
- cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950));
-
- cakeBakingService.saveNewTopping(new CakeToppingInfo("candies", 350));
- cakeBakingService.saveNewTopping(new CakeToppingInfo("cherry", 350));
+ private static CakeBakingService cakeBakingService = new CakeBakingServiceImpl();
- CakeInfo cake1 = new CakeInfo(new CakeToppingInfo("candies", 0),
- Arrays.asList(new CakeLayerInfo("chocolate", 0), new CakeLayerInfo("banana", 0),
- new CakeLayerInfo("strawberry", 0)));
- try {
- cakeBakingService.bakeNewCake(cake1);
- } catch (CakeBakingException e) {
- e.printStackTrace();
- }
- CakeInfo cake2 = new CakeInfo(new CakeToppingInfo("cherry", 0),
- Arrays.asList(new CakeLayerInfo("vanilla", 0), new CakeLayerInfo("lemon", 0),
- new CakeLayerInfo("strawberry", 0)));
- try {
- cakeBakingService.bakeNewCake(cake2);
- } catch (CakeBakingException e) {
- e.printStackTrace();
- }
- }
+ /**
+ * Application entry point
+ *
+ * @param args Command line parameters
+ */
+ public static void main(String[] args) {
+
+ // initialize example data
+ initializeData(cakeBakingService);
+
+ // create view and render it
+ CakeViewImpl cakeView = new CakeViewImpl(cakeBakingService);
+ cakeView.render();
+ }
+
+ /**
+ * Initializes the example data
+ *
+ * @param cakeBakingService
+ */
+ private static void initializeData(CakeBakingService cakeBakingService) {
+ cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200));
+ cakeBakingService.saveNewLayer(new CakeLayerInfo("banana", 900));
+ cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950));
+ cakeBakingService.saveNewLayer(new CakeLayerInfo("lemon", 950));
+ cakeBakingService.saveNewLayer(new CakeLayerInfo("vanilla", 950));
+ cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950));
+
+ cakeBakingService.saveNewTopping(new CakeToppingInfo("candies", 350));
+ cakeBakingService.saveNewTopping(new CakeToppingInfo("cherry", 350));
+
+ CakeInfo cake1 =
+ new CakeInfo(new CakeToppingInfo("candies", 0), Arrays.asList(new CakeLayerInfo(
+ "chocolate", 0), new CakeLayerInfo("banana", 0), new CakeLayerInfo("strawberry", 0)));
+ try {
+ cakeBakingService.bakeNewCake(cake1);
+ } catch (CakeBakingException e) {
+ e.printStackTrace();
+ }
+ CakeInfo cake2 =
+ new CakeInfo(new CakeToppingInfo("cherry", 0), Arrays.asList(
+ new CakeLayerInfo("vanilla", 0), new CakeLayerInfo("lemon", 0), new CakeLayerInfo(
+ "strawberry", 0)));
+ try {
+ cakeBakingService.bakeNewCake(cake2);
+ } catch (CakeBakingException e) {
+ e.printStackTrace();
+ }
+ }
}
diff --git a/layers/src/main/java/com/iluwatar/layers/Cake.java b/layers/src/main/java/com/iluwatar/layers/Cake.java
index 193ba5e3f..b251576bf 100644
--- a/layers/src/main/java/com/iluwatar/layers/Cake.java
+++ b/layers/src/main/java/com/iluwatar/layers/Cake.java
@@ -19,50 +19,50 @@ import javax.persistence.OneToOne;
@Entity
public class Cake {
- @Id
- @GeneratedValue
- private Long id;
+ @Id
+ @GeneratedValue
+ private Long id;
- @OneToOne(cascade=CascadeType.REMOVE)
- private CakeTopping topping;
-
- @OneToMany(cascade=CascadeType.REMOVE, fetch=FetchType.EAGER)
- private Set