Merge branch 'javadoc'

This commit is contained in:
Ilkka Seppala 2015-08-21 23:29:48 +03:00
commit cbab406e47
252 changed files with 3737 additions and 2819 deletions

View File

@ -1,29 +1,37 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
/** /**
* *
* The essence of the Abstract Factory pattern is a factory interface * The essence of the Abstract Factory pattern is a factory interface
* (KingdomFactory) and its implementations (ElfKingdomFactory, * ({@link KingdomFactory}) and its implementations ({@link ElfKingdomFactory},
* OrcKingdomFactory). * {@link OrcKingdomFactory}).
* * <p>
* The example uses both concrete implementations to create a king, a castle and * The example uses both concrete implementations to create a king, a castle and
* an army. * an army.
* *
*/ */
public class App { public class App {
public static void main(String[] args) { /**
createKingdom(new ElfKingdomFactory()); * Program entry point
createKingdom(new OrcKingdomFactory()); * @param args command line arguments
} */
public static void main(String[] args) {
public static void createKingdom(KingdomFactory factory) { createKingdom(new ElfKingdomFactory());
King king = factory.createKing(); createKingdom(new OrcKingdomFactory());
Castle castle = factory.createCastle(); }
Army army = factory.createArmy();
System.out.println("The kingdom was created."); /**
System.out.println(king); * Creates kingdom
System.out.println(castle); * @param factory
System.out.println(army); */
} public static void createKingdom(KingdomFactory factory) {
} King king = factory.createKing();
Castle castle = factory.createCastle();
Army army = factory.createArmy();
System.out.println("The kingdom was created.");
System.out.println(king);
System.out.println(castle);
System.out.println(army);
}
}

View File

@ -1,5 +1,10 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
public interface Army { /**
*
} * Army interface
*
*/
public interface Army {
}

View File

@ -1,5 +1,10 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
public interface Castle { /**
*
} * Castle interface
*
*/
public interface Castle {
}

View File

@ -1,10 +1,15 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
public class ElfArmy implements Army { /**
*
@Override * ElfArmy
public String toString() { *
return "This is the Elven Army!"; */
} public class ElfArmy implements Army {
} @Override
public String toString() {
return "This is the Elven Army!";
}
}

View File

@ -1,10 +1,15 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
public class ElfCastle implements Castle { /**
*
@Override * ElfCastle
public String toString() { *
return "This is the Elven castle!"; */
} public class ElfCastle implements Castle {
} @Override
public String toString() {
return "This is the Elven castle!";
}
}

View File

@ -1,10 +1,15 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
public class ElfKing implements King { /**
*
@Override * ElfKing
public String toString() { *
return "This is the Elven king!"; */
} public class ElfKing implements King {
} @Override
public String toString() {
return "This is the Elven king!";
}
}

View File

@ -1,22 +1,22 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
/** /**
* *
* Concrete factory. * ElfKingdomFactory concrete factory.
* *
*/ */
public class ElfKingdomFactory implements KingdomFactory { public class ElfKingdomFactory implements KingdomFactory {
public Castle createCastle() { public Castle createCastle() {
return new ElfCastle(); return new ElfCastle();
} }
public King createKing() { public King createKing() {
return new ElfKing(); return new ElfKing();
} }
public Army createArmy() { public Army createArmy() {
return new ElfArmy(); return new ElfArmy();
} }
} }

View File

@ -1,5 +1,10 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
public interface King { /**
*
} * King interface
*
*/
public interface King {
}

View File

@ -1,16 +1,16 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
/** /**
* *
* The factory interface. * KingdomFactory factory interface.
* *
*/ */
public interface KingdomFactory { public interface KingdomFactory {
Castle createCastle(); Castle createCastle();
King createKing(); King createKing();
Army createArmy(); Army createArmy();
} }

View File

@ -1,10 +1,15 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
public class OrcArmy implements Army { /**
*
@Override * OrcArmy
public String toString() { *
return "This is the Orcish Army!"; */
} public class OrcArmy implements Army {
} @Override
public String toString() {
return "This is the Orcish Army!";
}
}

View File

@ -1,10 +1,15 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
public class OrcCastle implements Castle { /**
*
@Override * OrcCastle
public String toString() { *
return "This is the Orcish castle!"; */
} public class OrcCastle implements Castle {
} @Override
public String toString() {
return "This is the Orcish castle!";
}
}

View File

@ -1,10 +1,15 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
public class OrcKing implements King { /**
*
@Override * OrcKing
public String toString() { *
return "This is the Orc king!"; */
} public class OrcKing implements King {
} @Override
public String toString() {
return "This is the Orc king!";
}
}

View File

@ -1,22 +1,22 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
/** /**
* *
* Concrete factory. * OrcKingdomFactory concrete factory.
* *
*/ */
public class OrcKingdomFactory implements KingdomFactory { public class OrcKingdomFactory implements KingdomFactory {
public Castle createCastle() { public Castle createCastle() {
return new OrcCastle(); return new OrcCastle();
} }
public King createKing() { public King createKing() {
return new OrcKing(); return new OrcKing();
} }
public Army createArmy() { public Army createArmy() {
return new OrcArmy(); return new OrcArmy();
} }
} }

View File

@ -1,13 +1,18 @@
package com.iluwatar.abstractfactory; package com.iluwatar.abstractfactory;
import org.junit.Test; import org.junit.Test;
import com.iluwatar.abstractfactory.App; import com.iluwatar.abstractfactory.App;
public class AppTest { /**
*
@Test * Application test
public void test() { *
String[] args = {}; */
App.main(args); public class AppTest {
}
} @Test
public void test() {
String[] args = {};
App.main(args);
}
}

View File

@ -1,21 +1,25 @@
package com.iluwatar.adapter; package com.iluwatar.adapter;
/** /**
* *
* There are two variations of the Adapter pattern: The class adapter implements * There are two variations of the Adapter pattern: The class adapter implements
* the adaptee's interface whereas the object adapter uses composition to * the adaptee's interface whereas the object adapter uses composition to
* contain the adaptee in the adapter object. This example uses the object * contain the adaptee in the adapter object. This example uses the object
* adapter approach. * adapter approach.
* * <p>
* The Adapter (GnomeEngineer) converts the interface of the target class * The Adapter ({@link GnomeEngineer}) converts the interface of the target class
* (GoblinGlider) into a suitable one expected by the client * ({@link GoblinGlider}) into a suitable one expected by the client
* (GnomeEngineeringManager). * ({@link GnomeEngineeringManager}).
* *
*/ */
public class App { public class App {
public static void main(String[] args) { /**
Engineer manager = new GnomeEngineeringManager(); * Program entry point
manager.operateDevice(); * @param args command line args
} */
} public static void main(String[] args) {
Engineer manager = new GnomeEngineeringManager();
manager.operateDevice();
}
}

View File

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

View File

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

View File

@ -1,14 +1,19 @@
package com.iluwatar.adapter; package com.iluwatar.adapter;
import org.junit.Test; import org.junit.Test;
import com.iluwatar.adapter.App; import com.iluwatar.adapter.App;
public class AppTest { /**
*
@Test * Application test
public void test() { *
String[] args = {}; */
App.main(args); public class AppTest {
}
} @Test
public void test() {
String[] args = {};
App.main(args);
}
}

View File

@ -3,29 +3,24 @@ package com.iluwatar.async.method.invocation;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* <p>
* This application demonstrates the async method invocation pattern. Key parts of the pattern are * This application demonstrates the async method invocation pattern. Key parts of the pattern are
* <code>AsyncResult</code> which is an intermediate container for an asynchronously evaluated value, * <code>AsyncResult</code> which is an intermediate container for an asynchronously evaluated value,
* <code>AsyncCallback</code> which can be provided to be executed on task completion and * <code>AsyncCallback</code> which can be provided to be executed on task completion and
* <code>AsyncExecutor</code> that manages the execution of the async tasks. * <code>AsyncExecutor</code> that manages the execution of the async tasks.
* </p>
* <p> * <p>
* The main method shows example flow of async invocations. The main thread starts multiple tasks with * The main method shows example flow of async invocations. The main thread starts multiple tasks with
* variable durations and then continues its own work. When the main thread has done it's job it collects * 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 * the results of the async tasks. Two of the tasks are handled with callbacks, meaning the callbacks are
* executed immediately when the tasks complete. * executed immediately when the tasks complete.
* </p>
* <p> * <p>
* Noteworthy difference of thread usage between the async results and callbacks is that the async results * Noteworthy difference of thread usage between the async results and callbacks is that the async results
* are collected in the main thread but the callbacks are executed within the worker threads. This should be * are collected in the main thread but the callbacks are executed within the worker threads. This should be
* noted when working with thread pools. * noted when working with thread pools.
* </p>
* <p> * <p>
* Java provides its own implementations of async method invocation pattern. FutureTask, CompletableFuture * Java provides its own implementations of async method invocation pattern. FutureTask, CompletableFuture
* and ExecutorService are the real world implementations of this pattern. But due to the nature of parallel * 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 * 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. * account but rather provides a simple version that helps to understand the pattern.
* </p>
* *
* @see AsyncResult * @see AsyncResult
* @see AsyncCallback * @see AsyncCallback

View File

@ -2,6 +2,13 @@ package com.iluwatar.async.method.invocation;
import java.util.Optional; import java.util.Optional;
/**
*
* AsyncCallback interface
*
* @param <T>
*
*/
public interface AsyncCallback<T> { public interface AsyncCallback<T> {
/** /**

View File

@ -3,6 +3,11 @@ package com.iluwatar.async.method.invocation;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
/**
*
* AsyncExecutor interface
*
*/
public interface AsyncExecutor { public interface AsyncExecutor {
/** /**

View File

@ -2,6 +2,12 @@ package com.iluwatar.async.method.invocation;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
/**
*
* AsyncResult interface
*
* @param <T>
*/
public interface AsyncResult<T> { public interface AsyncResult<T> {
/** /**

View File

@ -6,7 +6,9 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
/** /**
*
* Implementation of async executor that creates a new thread for every task. * Implementation of async executor that creates a new thread for every task.
*
*/ */
public class ThreadAsyncExecutor implements AsyncExecutor { public class ThreadAsyncExecutor implements AsyncExecutor {

View File

@ -2,6 +2,11 @@ package com.iluwatar.async.method.invocation;
import org.junit.Test; import org.junit.Test;
/**
*
* Application test
*
*/
public class AppTest { public class AppTest {
@Test @Test

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

After

Width:  |  Height:  |  Size: 52 KiB

View File

@ -1,18 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true" <class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
realizations="true" associations="true" dependencies="false" nesting-relationships="true"> realizations="true" associations="true" dependencies="false" nesting-relationships="true">
<class id="1" language="java" name="com.iluwatar.bridge.FlyingMagicWeaponImp" project="bridge" <class id="1" language="java" name="com.iluwatar.bridge.FlyingMagicWeaponImpl" project="bridge"
file="/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeaponImp.java" binary="false" corner="BOTTOM_RIGHT"> file="/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeaponImpl.java" binary="false" corner="BOTTOM_RIGHT">
<position height="105" width="192" x="193" y="297"/> <position height="-1" width="-1" x="515" y="591"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true"> sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/> <attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/> <operations public="true" package="true" protected="true" private="true" static="true"/>
</display> </display>
</class> </class>
<class id="2" language="java" name="com.iluwatar.bridge.SoulEatingMagicWeaponImp" project="bridge" <class id="2" language="java" name="com.iluwatar.bridge.SoulEatingMagicWeaponImpl" project="bridge"
file="/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeaponImp.java" binary="false" corner="BOTTOM_RIGHT"> file="/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeaponImpl.java" binary="false" corner="BOTTOM_RIGHT">
<position height="105" width="226" x="425" y="297"/> <position height="-1" width="-1" x="791" y="605"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true"> sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/> <attributes public="true" package="true" protected="true" private="true" static="true"/>
@ -21,25 +21,25 @@
</class> </class>
<class id="3" language="java" name="com.iluwatar.bridge.Stormbringer" project="bridge" <class id="3" language="java" name="com.iluwatar.bridge.Stormbringer" project="bridge"
file="/bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java" binary="false" corner="BOTTOM_RIGHT"> file="/bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java" binary="false" corner="BOTTOM_RIGHT">
<position height="160" width="125" x="425" y="442"/> <position height="-1" width="-1" x="791" y="788"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true"> sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/> <attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/> <operations public="true" package="true" protected="true" private="true" static="true"/>
</display> </display>
</class> </class>
<class id="4" language="java" name="com.iluwatar.bridge.MagicWeaponImp" project="bridge" <class id="4" language="java" name="com.iluwatar.bridge.MagicWeaponImpl" project="bridge"
file="/bridge/src/main/java/com/iluwatar/bridge/MagicWeaponImp.java" binary="false" corner="BOTTOM_RIGHT"> file="/bridge/src/main/java/com/iluwatar/bridge/MagicWeaponImpl.java" binary="false" corner="BOTTOM_RIGHT">
<position height="141" width="149" x="221" y="79"/> <position height="-1" width="-1" x="791" y="433"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true"> sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/> <attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/> <operations public="true" package="true" protected="true" private="true" static="true"/>
</display> </display>
</class> </class>
<class id="5" language="java" name="com.iluwatar.bridge.BlindingMagicWeaponImp" project="bridge" <class id="5" language="java" name="com.iluwatar.bridge.BlindingMagicWeaponImpl" project="bridge"
file="/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeaponImp.java" binary="false" corner="BOTTOM_RIGHT"> file="/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeaponImpl.java" binary="false" corner="BOTTOM_RIGHT">
<position height="105" width="208" x="691" y="297"/> <position height="-1" width="-1" x="1105" y="593"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true"> sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/> <attributes public="true" package="true" protected="true" private="true" static="true"/>
@ -48,7 +48,7 @@
</class> </class>
<class id="6" language="java" name="com.iluwatar.bridge.SoulEatingMagicWeapon" project="bridge" <class id="6" language="java" name="com.iluwatar.bridge.SoulEatingMagicWeapon" project="bridge"
file="/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeapon.java" binary="false" corner="BOTTOM_RIGHT"> file="/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeapon.java" binary="false" corner="BOTTOM_RIGHT">
<position height="178" width="347" x="410" y="79"/> <position height="-1" width="-1" x="380" y="21"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true"> sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/> <attributes public="true" package="true" protected="true" private="true" static="true"/>
@ -57,7 +57,7 @@
</class> </class>
<class id="7" language="java" name="com.iluwatar.bridge.Excalibur" project="bridge" <class id="7" language="java" name="com.iluwatar.bridge.Excalibur" project="bridge"
file="/bridge/src/main/java/com/iluwatar/bridge/Excalibur.java" binary="false" corner="BOTTOM_RIGHT"> file="/bridge/src/main/java/com/iluwatar/bridge/Excalibur.java" binary="false" corner="BOTTOM_RIGHT">
<position height="160" width="124" x="691" y="442"/> <position height="-1" width="-1" x="1105" y="782"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true"> sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/> <attributes public="true" package="true" protected="true" private="true" static="true"/>
@ -66,7 +66,7 @@
</class> </class>
<class id="8" language="java" name="com.iluwatar.bridge.Mjollnir" project="bridge" <class id="8" language="java" name="com.iluwatar.bridge.Mjollnir" project="bridge"
file="/bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java" binary="false" corner="BOTTOM_RIGHT"> file="/bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java" binary="false" corner="BOTTOM_RIGHT">
<position height="160" width="124" x="193" y="442"/> <position height="-1" width="-1" x="515" y="788"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true"> sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/> <attributes public="true" package="true" protected="true" private="true" static="true"/>
@ -75,7 +75,7 @@
</class> </class>
<class id="9" language="java" name="com.iluwatar.bridge.BlindingMagicWeapon" project="bridge" <class id="9" language="java" name="com.iluwatar.bridge.BlindingMagicWeapon" project="bridge"
file="/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeapon.java" binary="false" corner="BOTTOM_RIGHT"> file="/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeapon.java" binary="false" corner="BOTTOM_RIGHT">
<position height="178" width="313" x="797" y="79"/> <position height="-1" width="-1" x="791" y="14"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true"> sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/> <attributes public="true" package="true" protected="true" private="true" static="true"/>
@ -84,7 +84,7 @@
</class> </class>
<class id="10" language="java" name="com.iluwatar.bridge.MagicWeapon" project="bridge" <class id="10" language="java" name="com.iluwatar.bridge.MagicWeapon" project="bridge"
file="/bridge/src/main/java/com/iluwatar/bridge/MagicWeapon.java" binary="false" corner="BOTTOM_RIGHT"> file="/bridge/src/main/java/com/iluwatar/bridge/MagicWeapon.java" binary="false" corner="BOTTOM_RIGHT">
<position height="159" width="221" x="644" y="-120"/> <position height="-1" width="-1" x="791" y="237"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true"> sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/> <attributes public="true" package="true" protected="true" private="true" static="true"/>
@ -93,7 +93,7 @@
</class> </class>
<class id="11" language="java" name="com.iluwatar.bridge.FlyingMagicWeapon" project="bridge" <class id="11" language="java" name="com.iluwatar.bridge.FlyingMagicWeapon" project="bridge"
file="/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeapon.java" binary="false" corner="BOTTOM_RIGHT"> file="/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeapon.java" binary="false" corner="BOTTOM_RIGHT">
<position height="178" width="291" x="1150" y="79"/> <position height="-1" width="-1" x="1144" y="12"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" <display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true"> sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/> <attributes public="true" package="true" protected="true" private="true" static="true"/>
@ -101,48 +101,52 @@
</display> </display>
</class> </class>
<generalization id="12"> <generalization id="12">
<end type="SOURCE" refId="11"/> <end type="SOURCE" refId="8"/>
<end type="TARGET" refId="10"/> <end type="TARGET" refId="1"/>
</generalization> </generalization>
<generalization id="13"> <generalization id="13">
<end type="SOURCE" refId="1"/> <end type="SOURCE" refId="1"/>
<end type="TARGET" refId="4"/> <end type="TARGET" refId="4"/>
</generalization> </generalization>
<generalization id="14"> <generalization id="14">
<end type="SOURCE" refId="2"/>
<end type="TARGET" refId="4"/>
</generalization>
<generalization id="15">
<end type="SOURCE" refId="7"/>
<end type="TARGET" refId="5"/>
</generalization>
<generalization id="16">
<end type="SOURCE" refId="6"/>
<end type="TARGET" refId="10"/>
</generalization>
<generalization id="17">
<end type="SOURCE" refId="9"/> <end type="SOURCE" refId="9"/>
<end type="TARGET" refId="10"/> <end type="TARGET" refId="10"/>
</generalization> </generalization>
<generalization id="18"> <generalization id="15">
<end type="SOURCE" refId="3"/> <end type="SOURCE" refId="2"/>
<end type="TARGET" refId="2"/> <end type="TARGET" refId="4"/>
</generalization> </generalization>
<association id="19"> <association id="16">
<end type="SOURCE" refId="10" navigable="false"> <end type="SOURCE" refId="10" navigable="false">
<attribute id="20" name="imp"/> <attribute id="17" name="imp">
<multiplicity id="21" minimum="0" maximum="1"/> <position height="0" width="0" x="478" y="284"/>
</attribute>
<multiplicity id="18" minimum="0" maximum="1">
<position height="0" width="0" x="478" y="284"/>
</multiplicity>
</end> </end>
<end type="TARGET" refId="4" navigable="true"/> <end type="TARGET" refId="4" navigable="true"/>
<display labels="true" multiplicity="true"/> <display labels="true" multiplicity="true"/>
</association> </association>
<generalization id="22"> <generalization id="19">
<end type="SOURCE" refId="5"/> <end type="SOURCE" refId="5"/>
<end type="TARGET" refId="4"/> <end type="TARGET" refId="4"/>
</generalization> </generalization>
<generalization id="20">
<end type="SOURCE" refId="6"/>
<end type="TARGET" refId="10"/>
</generalization>
<generalization id="21">
<end type="SOURCE" refId="7"/>
<end type="TARGET" refId="5"/>
</generalization>
<generalization id="22">
<end type="SOURCE" refId="3"/>
<end type="TARGET" refId="2"/>
</generalization>
<generalization id="23"> <generalization id="23">
<end type="SOURCE" refId="8"/> <end type="SOURCE" refId="11"/>
<end type="TARGET" refId="1"/> <end type="TARGET" refId="10"/>
</generalization> </generalization>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" <classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true"> sort-features="false" accessors="true" visibility="true">

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

View File

@ -11,7 +11,7 @@ tags: Java
vary independently. vary independently.
![alt text](./etc/bridge_1.png "Bridge") ![alt text](./etc/bridge.png "Bridge")
**Applicability:** Use the Bridge pattern when **Applicability:** Use the Bridge pattern when

View File

@ -1,35 +1,39 @@
package com.iluwatar.bridge; package com.iluwatar.bridge;
/** /**
* *
* In Bridge pattern both abstraction (MagicWeapon) and implementation * In Bridge pattern both abstraction ({@link MagicWeapon}) and implementation
* (MagicWeaponImp) have their own class hierarchies. The interface of the * ({@link MagicWeaponImpl}) have their own class hierarchies. The interface of the
* implementations can be changed without affecting the clients. * implementations can be changed without affecting the clients.
* *
*/ */
public class App { public class App {
public static void main(String[] args) { /**
BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon( * Program entry point
new Excalibur()); * @param args command line args
blindingMagicWeapon.wield(); */
blindingMagicWeapon.blind(); public static void main(String[] args) {
blindingMagicWeapon.swing(); BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(
blindingMagicWeapon.unwield(); new Excalibur());
blindingMagicWeapon.wield();
FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon( blindingMagicWeapon.blind();
new Mjollnir()); blindingMagicWeapon.swing();
flyingMagicWeapon.wield(); blindingMagicWeapon.unwield();
flyingMagicWeapon.fly();
flyingMagicWeapon.swing(); FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(
flyingMagicWeapon.unwield(); new Mjollnir());
flyingMagicWeapon.wield();
SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon( flyingMagicWeapon.fly();
new Stormbringer()); flyingMagicWeapon.swing();
soulEatingMagicWeapon.wield(); flyingMagicWeapon.unwield();
soulEatingMagicWeapon.swing();
soulEatingMagicWeapon.eatSoul(); SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(
soulEatingMagicWeapon.unwield(); new Stormbringer());
soulEatingMagicWeapon.wield();
} soulEatingMagicWeapon.swing();
} soulEatingMagicWeapon.eatSoul();
soulEatingMagicWeapon.unwield();
}
}

View File

@ -1,33 +1,38 @@
package com.iluwatar.bridge; package com.iluwatar.bridge;
public class BlindingMagicWeapon extends MagicWeapon { /**
*
public BlindingMagicWeapon(BlindingMagicWeaponImp imp) { * BlindingMagicWeapon
super(imp); *
} */
public class BlindingMagicWeapon extends MagicWeapon {
@Override
public BlindingMagicWeaponImp getImp() { public BlindingMagicWeapon(BlindingMagicWeaponImpl imp) {
return (BlindingMagicWeaponImp) imp; super(imp);
} }
@Override @Override
public void wield() { public BlindingMagicWeaponImpl getImp() {
getImp().wieldImp(); return (BlindingMagicWeaponImpl) imp;
} }
@Override @Override
public void swing() { public void wield() {
getImp().swingImp(); getImp().wieldImp();
} }
@Override @Override
public void unwield() { public void swing() {
getImp().unwieldImp(); getImp().swingImp();
} }
public void blind() { @Override
getImp().blindImp(); public void unwield() {
} getImp().unwieldImp();
}
}
public void blind() {
getImp().blindImp();
}
}

View File

@ -1,7 +0,0 @@
package com.iluwatar.bridge;
public abstract class BlindingMagicWeaponImp extends MagicWeaponImp {
public abstract void blindImp();
}

View File

@ -0,0 +1,12 @@
package com.iluwatar.bridge;
/**
*
* BlindingMagicWeaponImpl
*
*/
public abstract class BlindingMagicWeaponImpl extends MagicWeaponImpl {
public abstract void blindImp();
}

View File

@ -1,26 +1,31 @@
package com.iluwatar.bridge; package com.iluwatar.bridge;
public class Excalibur extends BlindingMagicWeaponImp { /**
*
@Override * Excalibur
public void wieldImp() { *
System.out.println("wielding Excalibur"); */
} public class Excalibur extends BlindingMagicWeaponImpl {
@Override @Override
public void swingImp() { public void wieldImp() {
System.out.println("swinging Excalibur"); System.out.println("wielding Excalibur");
} }
@Override @Override
public void unwieldImp() { public void swingImp() {
System.out.println("unwielding Excalibur"); System.out.println("swinging Excalibur");
} }
@Override @Override
public void blindImp() { public void unwieldImp() {
System.out System.out.println("unwielding Excalibur");
.println("bright light streams from Excalibur blinding the enemy"); }
}
@Override
} public void blindImp() {
System.out
.println("bright light streams from Excalibur blinding the enemy");
}
}

View File

@ -1,32 +1,37 @@
package com.iluwatar.bridge; package com.iluwatar.bridge;
public class FlyingMagicWeapon extends MagicWeapon { /**
*
public FlyingMagicWeapon(FlyingMagicWeaponImp imp) { * FlyingMagicWeapon
super(imp); *
} */
public class FlyingMagicWeapon extends MagicWeapon {
public FlyingMagicWeaponImp getImp() {
return (FlyingMagicWeaponImp) imp; public FlyingMagicWeapon(FlyingMagicWeaponImpl imp) {
} super(imp);
}
@Override
public void wield() { public FlyingMagicWeaponImpl getImp() {
getImp().wieldImp(); return (FlyingMagicWeaponImpl) imp;
} }
@Override @Override
public void swing() { public void wield() {
getImp().swingImp(); getImp().wieldImp();
} }
@Override @Override
public void unwield() { public void swing() {
getImp().unwieldImp(); getImp().swingImp();
} }
public void fly() { @Override
getImp().flyImp(); public void unwield() {
} getImp().unwieldImp();
}
}
public void fly() {
getImp().flyImp();
}
}

View File

@ -1,7 +0,0 @@
package com.iluwatar.bridge;
public abstract class FlyingMagicWeaponImp extends MagicWeaponImp {
public abstract void flyImp();
}

View File

@ -0,0 +1,12 @@
package com.iluwatar.bridge;
/**
*
* FlyingMagicWeaponImpl
*
*/
public abstract class FlyingMagicWeaponImpl extends MagicWeaponImpl {
public abstract void flyImp();
}

View File

@ -1,26 +1,26 @@
package com.iluwatar.bridge; package com.iluwatar.bridge;
/** /**
* *
* Abstraction interface. * MagicWeapon
* *
*/ */
public abstract class MagicWeapon { public abstract class MagicWeapon {
protected MagicWeaponImp imp; protected MagicWeaponImpl imp;
public MagicWeapon(MagicWeaponImp imp) { public MagicWeapon(MagicWeaponImpl imp) {
this.imp = imp; this.imp = imp;
} }
public abstract void wield(); public abstract void wield();
public abstract void swing(); public abstract void swing();
public abstract void unwield(); public abstract void unwield();
public MagicWeaponImp getImp() { public MagicWeaponImpl getImp() {
return imp; return imp;
} }
} }

View File

@ -1,16 +1,16 @@
package com.iluwatar.bridge; package com.iluwatar.bridge;
/** /**
* *
* Implementation interface. * MagicWeaponImpl
* *
*/ */
public abstract class MagicWeaponImp { public abstract class MagicWeaponImpl {
public abstract void wieldImp(); public abstract void wieldImp();
public abstract void swingImp(); public abstract void swingImp();
public abstract void unwieldImp(); public abstract void unwieldImp();
} }

View File

@ -1,26 +1,31 @@
package com.iluwatar.bridge; package com.iluwatar.bridge;
public class Mjollnir extends FlyingMagicWeaponImp { /**
*
@Override * Mjollnir
public void wieldImp() { *
System.out.println("wielding Mjollnir"); */
} public class Mjollnir extends FlyingMagicWeaponImpl {
@Override @Override
public void swingImp() { public void wieldImp() {
System.out.println("swinging Mjollnir"); System.out.println("wielding Mjollnir");
} }
@Override @Override
public void unwieldImp() { public void swingImp() {
System.out.println("unwielding Mjollnir"); System.out.println("swinging Mjollnir");
} }
@Override @Override
public void flyImp() { public void unwieldImp() {
System.out System.out.println("unwielding Mjollnir");
.println("Mjollnir hits the enemy in the air and returns back to the owner's hand"); }
}
@Override
} public void flyImp() {
System.out
.println("Mjollnir hits the enemy in the air and returns back to the owner's hand");
}
}

View File

@ -1,33 +1,38 @@
package com.iluwatar.bridge; package com.iluwatar.bridge;
public class SoulEatingMagicWeapon extends MagicWeapon { /**
*
public SoulEatingMagicWeapon(SoulEatingMagicWeaponImp imp) { * SoulEatingMagicWeapon
super(imp); *
} */
public class SoulEatingMagicWeapon extends MagicWeapon {
@Override
public SoulEatingMagicWeaponImp getImp() { public SoulEatingMagicWeapon(SoulEatingMagicWeaponImpl imp) {
return (SoulEatingMagicWeaponImp) imp; super(imp);
} }
@Override @Override
public void wield() { public SoulEatingMagicWeaponImpl getImp() {
getImp().wieldImp(); return (SoulEatingMagicWeaponImpl) imp;
} }
@Override @Override
public void swing() { public void wield() {
getImp().swingImp(); getImp().wieldImp();
} }
@Override @Override
public void unwield() { public void swing() {
getImp().unwieldImp(); getImp().swingImp();
} }
public void eatSoul() { @Override
getImp().eatSoulImp(); public void unwield() {
} getImp().unwieldImp();
}
}
public void eatSoul() {
getImp().eatSoulImp();
}
}

View File

@ -1,7 +0,0 @@
package com.iluwatar.bridge;
public abstract class SoulEatingMagicWeaponImp extends MagicWeaponImp {
public abstract void eatSoulImp();
}

View File

@ -0,0 +1,12 @@
package com.iluwatar.bridge;
/**
*
* SoulEatingMagicWeaponImpl
*
*/
public abstract class SoulEatingMagicWeaponImpl extends MagicWeaponImpl {
public abstract void eatSoulImp();
}

View File

@ -1,25 +1,30 @@
package com.iluwatar.bridge; package com.iluwatar.bridge;
public class Stormbringer extends SoulEatingMagicWeaponImp { /**
*
@Override * Stormbringer
public void wieldImp() { *
System.out.println("wielding Stormbringer"); */
} public class Stormbringer extends SoulEatingMagicWeaponImpl {
@Override @Override
public void swingImp() { public void wieldImp() {
System.out.println("swinging Stormbringer"); System.out.println("wielding Stormbringer");
} }
@Override @Override
public void unwieldImp() { public void swingImp() {
System.out.println("unwielding Stormbringer"); System.out.println("swinging Stormbringer");
} }
@Override @Override
public void eatSoulImp() { public void unwieldImp() {
System.out.println("Stormbringer devours the enemy's soul"); System.out.println("unwielding Stormbringer");
} }
} @Override
public void eatSoulImp() {
System.out.println("Stormbringer devours the enemy's soul");
}
}

View File

@ -1,14 +1,19 @@
package com.iluwatar.bridge; package com.iluwatar.bridge;
import org.junit.Test; import org.junit.Test;
import com.iluwatar.bridge.App; import com.iluwatar.bridge.App;
public class AppTest { /**
*
@Test * Application test
public void test() { *
String[] args = {}; */
App.main(args); public class AppTest {
}
} @Test
public void test() {
String[] args = {};
App.main(args);
}
}

View File

@ -1,38 +1,42 @@
package com.iluwatar.builder; package com.iluwatar.builder;
import com.iluwatar. builder.Hero.HeroBuilder; import com.iluwatar. builder.Hero.HeroBuilder;
/** /**
* *
* This is the Builder pattern variation as described by Joshua Bloch in * This is the Builder pattern variation as described by Joshua Bloch in
* Effective Java 2nd Edition. * Effective Java 2nd Edition.
* * <p>
* We want to build Hero objects, but its construction is complex because of the * We want to build {@link Hero} objects, but its construction is complex because of the
* many parameters needed. To aid the user we introduce HeroBuilder class. * many parameters needed. To aid the user we introduce {@link HeroBuilder} class.
* HeroBuilder takes the minimum parameters to build Hero object in its * {@link HeroBuilder} takes the minimum parameters to build {@link Hero} object in its
* constructor. After that additional configuration for the Hero object can be * constructor. After that additional configuration for the {@link Hero} object can be
* done using the fluent HeroBuilder interface. When configuration is ready the * done using the fluent {@link HeroBuilder} interface. When configuration is ready the
* build method is called to receive the final Hero object. * build method is called to receive the final {@link Hero} object.
* *
*/ */
public class App { public class App {
public static void main(String[] args) { /**
* Program entry point
Hero mage = new HeroBuilder(Profession.MAGE, "Riobard") * @param args command line args
.withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER) */
.build(); public static void main(String[] args) {
System.out.println(mage);
Hero mage = new HeroBuilder(Profession.MAGE, "Riobard")
Hero warrior = new HeroBuilder(Profession.WARRIOR, "Amberjill") .withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER)
.withHairColor(HairColor.BLOND) .build();
.withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL) System.out.println(mage);
.withWeapon(Weapon.SWORD).build();
System.out.println(warrior); Hero warrior = new HeroBuilder(Profession.WARRIOR, "Amberjill")
.withHairColor(HairColor.BLOND)
Hero thief = new HeroBuilder(Profession.THIEF, "Desmond") .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL)
.withHairType(HairType.BALD).withWeapon(Weapon.BOW).build(); .withWeapon(Weapon.SWORD).build();
System.out.println(thief); System.out.println(warrior);
} Hero thief = new HeroBuilder(Profession.THIEF, "Desmond")
} .withHairType(HairType.BALD).withWeapon(Weapon.BOW).build();
System.out.println(thief);
}
}

View File

@ -1,17 +1,22 @@
package com.iluwatar.builder; package com.iluwatar.builder;
public enum Armor { /**
*
CLOTHES("clothes"), LEATHER("leather"), CHAIN_MAIL("chain mail"), PLATE_MAIL("plate mail"); * Armor enumeration
*
private String title; */
public enum Armor {
Armor(String title) {
this.title = title; CLOTHES("clothes"), LEATHER("leather"), CHAIN_MAIL("chain mail"), PLATE_MAIL("plate mail");
}
private String title;
@Override
public String toString() { Armor(String title) {
return title; this.title = title;
} }
}
@Override
public String toString() {
return title;
}
}

View File

@ -1,12 +1,17 @@
package com.iluwatar.builder; package com.iluwatar.builder;
public enum HairColor { /**
*
WHITE, BLOND, RED, BROWN, BLACK; * HairColor enumeration
*
@Override */
public String toString() { public enum HairColor {
return name().toLowerCase();
} WHITE, BLOND, RED, BROWN, BLACK;
} @Override
public String toString() {
return name().toLowerCase();
}
}

View File

@ -1,17 +1,22 @@
package com.iluwatar.builder; package com.iluwatar.builder;
public enum HairType { /**
*
BALD("bald"), SHORT("short"), CURLY("curly"), LONG_STRAIGHT("long straight"), LONG_CURLY("long curly"); * HairType enumeration
*
private String title; */
public enum HairType {
HairType(String title) {
this.title = title; BALD("bald"), SHORT("short"), CURLY("curly"), LONG_STRAIGHT("long straight"), LONG_CURLY("long curly");
}
private String title;
@Override
public String toString() { HairType(String title) {
return title; this.title = title;
} }
}
@Override
public String toString() {
return title;
}
}

View File

@ -2,7 +2,7 @@ package com.iluwatar.builder;
/** /**
* *
* The class with many parameters. * Hero, the class with many parameters.
* *
*/ */
public class Hero { public class Hero {

View File

@ -1,12 +1,17 @@
package com.iluwatar.builder; package com.iluwatar.builder;
public enum Profession { /**
*
WARRIOR, THIEF, MAGE, PRIEST; * Profession enumeration
*
@Override */
public String toString() { public enum Profession {
return name().toLowerCase();
} WARRIOR, THIEF, MAGE, PRIEST;
} @Override
public String toString() {
return name().toLowerCase();
}
}

View File

@ -1,12 +1,17 @@
package com.iluwatar.builder; package com.iluwatar.builder;
public enum Weapon { /**
*
DAGGER, SWORD, AXE, WARHAMMER, BOW; * Weapon enumeration
*
@Override */
public String toString() { public enum Weapon {
return name().toLowerCase();
} DAGGER, SWORD, AXE, WARHAMMER, BOW;
} @Override
public String toString() {
return name().toLowerCase();
}
}

View File

@ -1,14 +1,19 @@
package com.iluwatar.builder; package com.iluwatar.builder;
import org.junit.Test; import org.junit.Test;
import com.iluwatar. builder.App; import com.iluwatar. builder.App;
public class AppTest { /**
*
@Test * Application test
public void test() { *
String[] args = {}; */
App.main(args); public class AppTest {
}
} @Test
public void test() {
String[] args = {};
App.main(args);
}
}

View File

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

View File

@ -2,7 +2,7 @@ package com.iluwatar.business.delegate;
/** /**
* *
* BusinessDelegate separates presentation and business tiers * BusinessDelegate separates the presentation and business tiers
* *
*/ */
public class BusinessDelegate { public class BusinessDelegate {

View File

@ -4,6 +4,11 @@ import org.junit.Test;
import com.iluwatar.business.delegate.App; import com.iluwatar.business.delegate.App;
/**
*
* Application test
*
*/
public class AppTest { public class AppTest {
@Test @Test

View File

@ -1,8 +1,10 @@
package com.iluwatar.callback; package com.iluwatar.callback;
/** /**
* Callback pattern is more native for functional languages where function is treated as first-class citizen. *
* Prior to Java8 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 class App {

View File

@ -1,7 +1,9 @@
package com.iluwatar.callback; package com.iluwatar.callback;
/** /**
*
* Callback interface * Callback interface
*
*/ */
public interface Callback { public interface Callback {

View File

@ -1,7 +1,9 @@
package com.iluwatar.callback; package com.iluwatar.callback;
/** /**
*
* Implementation of task that need to be executed * Implementation of task that need to be executed
*
*/ */
public class SimpleTask extends Task { public class SimpleTask extends Task {

View File

@ -1,7 +1,9 @@
package com.iluwatar.callback; package com.iluwatar.callback;
/** /**
*
* Template-method class for callback hook execution * Template-method class for callback hook execution
*
*/ */
public abstract class Task { public abstract class Task {

View File

@ -4,6 +4,11 @@ import org.junit.Test;
import com.iluwatar.callback.App; import com.iluwatar.callback.App;
/**
*
* Application test
*
*/
public class AppTest { public class AppTest {
@Test @Test

View File

@ -1,22 +1,26 @@
package com.iluwatar.chain; package com.iluwatar.chain;
/** /**
* *
* Chain of Responsibility organizes request handlers (RequestHandler) into a * Chain of Responsibility organizes request handlers ({@link RequestHandler}) into a
* chain where each handler has a chance to act on the request on its turn. In * chain where each handler has a chance to act on the request on its turn. In
* this example the king (OrcKing) makes requests and the military orcs * this example the king ({@link OrcKing}) makes requests and the military orcs
* (OrcCommander, OrcOfficer, OrcSoldier) form the handler chain. * ({@link OrcCommander}, {@link OrcOfficer}, {@link OrcSoldier}) form the handler chain.
* *
*/ */
public class App { public class App {
public static void main(String[] args) { /**
* Program entry point
OrcKing king = new OrcKing(); * @param args command line args
king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); */
king.makeRequest(new Request(RequestType.TORTURE_PRISONER, public static void main(String[] args) {
"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"));
}
}

View File

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

View File

@ -1,24 +1,24 @@
package com.iluwatar.chain; package com.iluwatar.chain;
/** /**
* *
* Makes requests that are handled by the chain. * OrcKing makes requests that are handled by the chain.
* *
*/ */
public class OrcKing { public class OrcKing {
RequestHandler chain; RequestHandler chain;
public OrcKing() { public OrcKing() {
buildChain(); buildChain();
} }
private void buildChain() { private void buildChain() {
chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null))); chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null)));
} }
public void makeRequest(Request req) { public void makeRequest(Request req) {
chain.handleRequest(req); chain.handleRequest(req);
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,14 +1,19 @@
package com.iluwatar.chain; package com.iluwatar.chain;
import org.junit.Test; import org.junit.Test;
import com.iluwatar.chain.App; import com.iluwatar.chain.App;
public class AppTest { /**
*
@Test * Application test
public void test() { *
String[] args = {}; */
App.main(args); public class AppTest {
}
} @Test
public void test() {
String[] args = {};
App.main(args);
}
}

View File

@ -3,15 +3,15 @@ package com.iluwatar.command;
/** /**
* *
* In Command pattern actions are objects that can be executed and undone. * In Command pattern actions are objects that can be executed and undone.
* * <p>
* Four terms always associated with the command pattern are command, receiver, invoker and client. A command * Four terms always associated with the command pattern are command, receiver, invoker and client. A command
* object (spell) knows about receiver (target) and invokes a method of the receiver. Values for parameters of * 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) * 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 * 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 * 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 * 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. * which points. To execute a command, it passes the command object to the invoker object.
* * <p>
* In other words, in this example the wizard casts spells on the goblin. The wizard keeps track of the previous * 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 * spells cast, so it is easy to undo them. In addition, the wizard keeps track of the spells undone, so they
* can be redone. * can be redone.
@ -20,6 +20,10 @@ package com.iluwatar.command;
*/ */
public class App { public class App {
/**
* Program entry point
* @param args command line args
*/
public static void main(String[] args) { public static void main(String[] args) {
Wizard wizard = new Wizard(); Wizard wizard = new Wizard();
Goblin goblin = new Goblin(); Goblin goblin = new Goblin();

View File

@ -1,14 +1,19 @@
package com.iluwatar.command; package com.iluwatar.command;
import org.junit.Test; import org.junit.Test;
import com.iluwatar.command.App; import com.iluwatar.command.App;
public class AppTest { /**
*
@Test * Application test
public void test() { *
String[] args = {}; */
App.main(args); public class AppTest {
}
} @Test
public void test() {
String[] args = {};
App.main(args);
}
}

View File

@ -1,25 +1,29 @@
package com.iluwatar.composite; package com.iluwatar.composite;
/** /**
* *
* With Composite we can treat tree hierarchies of objects with uniform * With Composite we can treat tree hierarchies of objects with uniform
* interface (LetterComposite). In this example we have sentences composed of * interface ({@link LetterComposite}). In this example we have sentences composed of
* words composed of letters. * words composed of letters.
* *
*/ */
public class App { public class App {
public static void main(String[] args) { /**
System.out.println("Message from the orcs: "); * Program entry point
* @param args command line args
LetterComposite orcMessage = new Messenger().messageFromOrcs(); */
orcMessage.print(); public static void main(String[] args) {
System.out.println("Message from the orcs: ");
System.out.println("\n");
LetterComposite orcMessage = new Messenger().messageFromOrcs();
System.out.println("Message from the elves: "); orcMessage.print();
LetterComposite elfMessage = new Messenger().messageFromElves(); System.out.println("\n");
elfMessage.print();
} System.out.println("Message from the elves: ");
}
LetterComposite elfMessage = new Messenger().messageFromElves();
elfMessage.print();
}
}

View File

@ -1,21 +1,26 @@
package com.iluwatar.composite; package com.iluwatar.composite;
public class Letter extends LetterComposite { /**
*
private char c; * Letter
*
public Letter(char c) { */
this.c = c; public class Letter extends LetterComposite {
}
private char c;
@Override
protected void printThisBefore() { public Letter(char c) {
System.out.print(c); this.c = c;
} }
@Override @Override
protected void printThisAfter() { protected void printThisBefore() {
// nop System.out.print(c);
} }
} @Override
protected void printThisAfter() {
// nop
}
}

View File

@ -1,53 +1,58 @@
package com.iluwatar.composite; package com.iluwatar.composite;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public class Messenger { /**
*
LetterComposite messageFromOrcs() { * Messenger
*
List<Word> words = new ArrayList<Word>(); */
public class Messenger {
words.add(new Word(Arrays.asList(new Letter('W'), new Letter('h'),
new Letter('e'), new Letter('r'), new Letter('e')))); LetterComposite messageFromOrcs() {
words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'),
new Letter('e'), new Letter('r'), new Letter('e')))); List<Word> words = new ArrayList<Word>();
words.add(new Word(Arrays.asList(new Letter('i'), new Letter('s'))));
words.add(new Word(Arrays.asList(new Letter('a')))); words.add(new Word(Arrays.asList(new Letter('W'), new Letter('h'),
words.add(new Word(Arrays.asList(new Letter('w'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e'))));
new Letter('i'), new Letter('p')))); words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'),
words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e'))));
new Letter('e'), new Letter('r'), new Letter('e')))); words.add(new Word(Arrays.asList(new Letter('i'), new Letter('s'))));
words.add(new Word(Arrays.asList(new Letter('i'), new Letter('s')))); words.add(new Word(Arrays.asList(new Letter('a'))));
words.add(new Word(Arrays.asList(new Letter('a')))); words.add(new Word(Arrays.asList(new Letter('w'), new Letter('h'),
words.add(new Word(Arrays.asList(new Letter('w'), new Letter('a'), new Letter('i'), new Letter('p'))));
new Letter('y')))); words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'),
new Letter('e'), new Letter('r'), new Letter('e'))));
return new Sentence(words); words.add(new Word(Arrays.asList(new Letter('i'), new Letter('s'))));
words.add(new Word(Arrays.asList(new Letter('a'))));
} words.add(new Word(Arrays.asList(new Letter('w'), new Letter('a'),
new Letter('y'))));
LetterComposite messageFromElves() {
return new Sentence(words);
List<Word> words = new ArrayList<Word>();
}
words.add(new Word(Arrays.asList(new Letter('M'), new Letter('u'),
new Letter('c'), new Letter('h')))); LetterComposite messageFromElves() {
words.add(new Word(Arrays.asList(new Letter('w'), new Letter('i'),
new Letter('n'), new Letter('d')))); List<Word> words = new ArrayList<Word>();
words.add(new Word(Arrays.asList(new Letter('p'), new Letter('o'),
new Letter('u'), new Letter('r'), new Letter('s')))); words.add(new Word(Arrays.asList(new Letter('M'), new Letter('u'),
words.add(new Word(Arrays.asList(new Letter('f'), new Letter('r'), new Letter('c'), new Letter('h'))));
new Letter('o'), new Letter('m')))); words.add(new Word(Arrays.asList(new Letter('w'), new Letter('i'),
words.add(new Word(Arrays.asList(new Letter('y'), new Letter('o'), new Letter('n'), new Letter('d'))));
new Letter('u'), new Letter('r')))); words.add(new Word(Arrays.asList(new Letter('p'), new Letter('o'),
words.add(new Word(Arrays.asList(new Letter('m'), new Letter('o'), new Letter('u'), new Letter('r'), new Letter('s'))));
new Letter('u'), new Letter('t'), new Letter('h')))); words.add(new Word(Arrays.asList(new Letter('f'), new Letter('r'),
new Letter('o'), new Letter('m'))));
return new Sentence(words); words.add(new Word(Arrays.asList(new Letter('y'), new Letter('o'),
new Letter('u'), new Letter('r'))));
} words.add(new Word(Arrays.asList(new Letter('m'), new Letter('o'),
new Letter('u'), new Letter('t'), new Letter('h'))));
}
return new Sentence(words);
}
}

View File

@ -1,23 +1,28 @@
package com.iluwatar.composite; package com.iluwatar.composite;
import java.util.List; import java.util.List;
public class Sentence extends LetterComposite { /**
*
public Sentence(List<Word> words) { * Sentence
for (Word w : words) { *
this.add(w); */
} public class Sentence extends LetterComposite {
}
public Sentence(List<Word> words) {
@Override for (Word w : words) {
protected void printThisBefore() { this.add(w);
// nop }
} }
@Override @Override
protected void printThisAfter() { protected void printThisBefore() {
System.out.print("."); // nop
} }
} @Override
protected void printThisAfter() {
System.out.print(".");
}
}

View File

@ -1,23 +1,28 @@
package com.iluwatar.composite; package com.iluwatar.composite;
import java.util.List; import java.util.List;
public class Word extends LetterComposite { /**
*
public Word(List<Letter> letters) { * Word
for (Letter l : letters) { *
this.add(l); */
} public class Word extends LetterComposite {
}
public Word(List<Letter> letters) {
@Override for (Letter l : letters) {
protected void printThisBefore() { this.add(l);
System.out.print(" "); }
} }
@Override @Override
protected void printThisAfter() { protected void printThisBefore() {
// nop System.out.print(" ");
} }
} @Override
protected void printThisAfter() {
// nop
}
}

View File

@ -1,14 +1,19 @@
package com.iluwatar.composite; package com.iluwatar.composite;
import org.junit.Test; import org.junit.Test;
import com.iluwatar.composite.App; import com.iluwatar.composite.App;
public class AppTest { /**
*
@Test * Application test
public void test() { *
String[] args = {}; */
App.main(args); public class AppTest {
}
} @Test
public void test() {
String[] args = {};
App.main(args);
}
}

View File

@ -1,47 +1,56 @@
package com.iluwatar.dao; package com.iluwatar.dao;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* *
* With the DAO pattern, we can use various method calls to retrieve/add/delete/update data without directly * 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 operations(CRUD): select, add, update, and delete. * interacting with the data. The below example demonstrates basic operations(CRUD): select, add, update, and delete.
*/ *
public class App { */
public class App {
public static void main(String[] args) {
/**
CustomerDaoImpl customerDao = new CustomerDaoImpl(generateSampleCustomers()); * Program entry point
* @param args command line args
System.out.println("customerDao.getAllCustomers(): " + customerDao.getAllCustomers()); */
System.out.println("customerDao.getCusterById(2): " + customerDao.getCusterById(2)); public static void main(String[] args) {
Customer customer = new Customer(4, "Dan", "Danson"); CustomerDaoImpl customerDao = new CustomerDaoImpl(generateSampleCustomers());
customerDao.addCustomer(customer);
System.out.println("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
System.out.println("customerDao.getAllCustomers(): " + customerDao.getAllCustomers()); System.out.println("customerDao.getCusterById(2): " + customerDao.getCusterById(2));
customer.setFirstName("Daniel"); Customer customer = new Customer(4, "Dan", "Danson");
customer.setLastName("Danielson"); customerDao.addCustomer(customer);
customerDao.updateCustomer(customer);
System.out.println("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
System.out.println("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
customer.setFirstName("Daniel");
customerDao.deleteCustomer(customer); customer.setLastName("Danielson");
customerDao.updateCustomer(customer);
System.out.println("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
} System.out.println("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
public static List<Customer> generateSampleCustomers() { customerDao.deleteCustomer(customer);
Customer customer1 = new Customer(1, "Adam", "Adamson");
Customer customer2 = new Customer(2, "Bob", "Bobson"); System.out.println("customerDao.getAllCustomers(): " + customerDao.getAllCustomers());
Customer customer3 = new Customer(3, "Carl", "Carlson"); }
List<Customer> customers = new ArrayList<Customer>(); /**
customers.add(customer1); * Generate customers
customers.add(customer2); * @return list of customers
customers.add(customer3); */
return customers; public static List<Customer> generateSampleCustomers() {
} Customer customer1 = new Customer(1, "Adam", "Adamson");
} Customer customer2 = new Customer(2, "Bob", "Bobson");
Customer customer3 = new Customer(3, "Carl", "Carlson");
List<Customer> customers = new ArrayList<Customer>();
customers.add(customer1);
customers.add(customer2);
customers.add(customer3);
return customers;
}
}

View File

@ -1,6 +1,12 @@
package com.iluwatar.dao; package com.iluwatar.dao;
/**
*
* Customer
*
*/
public class Customer { public class Customer {
private int id; private int id;
private String firstName; private String firstName;
private String lastName; private String lastName;

View File

@ -2,7 +2,13 @@ package com.iluwatar.dao;
import java.util.List; import java.util.List;
/**
*
* CustomerDao
*
*/
public interface CustomerDao { public interface CustomerDao {
public List<Customer> getAllCustomers(); public List<Customer> getAllCustomers();
public Customer getCusterById(int id); public Customer getCusterById(int id);
public void addCustomer(Customer customer); public void addCustomer(Customer customer);

View File

@ -3,11 +3,13 @@ package com.iluwatar.dao;
import java.util.List; import java.util.List;
/** /**
*
* The data access object (DAO) is an object that provides an abstract interface to some type of database or other persistence mechanism. * The data access object (DAO) is an object that provides an abstract interface to some type of database or other persistence mechanism.
* By mapping application calls to the persistence layer, DAO provide some specific data operations without exposing details of the database. * By mapping application calls to the persistence layer, DAO provide some specific data operations without exposing details of the database.
* This isolation supports the Single responsibility principle. It separates what data accesses the application needs, in terms of * This isolation supports the Single responsibility principle. It separates what data accesses the application needs, in terms of
* domain-specific objects and data types (the public interface of the DAO), from how these needs can be satisfied with a specific DBMS, * domain-specific objects and data types (the public interface of the DAO), from how these needs can be satisfied with a specific DBMS,
* database schema, etc. * database schema, etc.
*
*/ */
public class CustomerDaoImpl implements CustomerDao { public class CustomerDaoImpl implements CustomerDao {

View File

@ -1,14 +1,19 @@
package com.iluwatar.dao; package com.iluwatar.dao;
import org.junit.Test; import org.junit.Test;
import com.iluwatar.dao.App; import com.iluwatar.dao.App;
public class AppTest { /**
*
@Test * Application test
public void test() { *
String[] args = {}; */
App.main(args); public class AppTest {
}
} @Test
public void test() {
String[] args = {};
App.main(args);
}
}

View File

@ -1,29 +1,33 @@
package com.iluwatar.decorator; package com.iluwatar.decorator;
/** /**
* *
* Decorator pattern is more flexible alternative to subclassing. The decorator * Decorator pattern is a more flexible alternative to subclassing. The decorator
* class implements the same interface as the target and uses composition to * class implements the same interface as the target and uses composition to
* "decorate" calls to the target. * "decorate" calls to the target.
* * <p>
* Using decorator pattern it is possible to change class behavior during * Using decorator pattern it is possible to change class behavior during
* runtime, as the example shows. * runtime, as the example shows.
* *
*/ */
public class App { public class App {
public static void main(String[] args) { /**
* Program entry point
// simple troll * @param args command line args
System.out.println("A simple looking troll approaches."); */
Hostile troll = new Troll(); public static void main(String[] args) {
troll.attack();
troll.fleeBattle(); // simple troll
System.out.println("A simple looking troll approaches.");
// change the behavior of the simple troll by adding a decorator Hostile troll = new Troll();
System.out.println("\nA smart looking troll surprises you."); troll.attack();
Hostile smart = new SmartTroll(troll); troll.fleeBattle();
smart.attack();
smart.fleeBattle(); // 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();
}
}

View File

@ -1,30 +1,30 @@
package com.iluwatar.decorator; package com.iluwatar.decorator;
/** /**
* SmartTroll is a decorator for Hostile objects. * SmartTroll is a decorator for {@link Hostile} objects.
* The calls to the Hostile interface are intercepted * The calls to the {@link Hostile} interface are intercepted
* and decorated. Finally the calls are delegated * and decorated. Finally the calls are delegated
* to the decorated Hostile object. * to the decorated {@link Hostile} object.
* *
*/ */
public class SmartTroll implements Hostile { public class SmartTroll implements Hostile {
private Hostile decorated; private Hostile decorated;
public SmartTroll(Hostile decorated) { public SmartTroll(Hostile decorated) {
this.decorated = decorated; this.decorated = decorated;
} }
@Override @Override
public void attack() { public void attack() {
System.out.println("The troll throws a rock at you!"); System.out.println("The troll throws a rock at you!");
decorated.attack(); decorated.attack();
} }
@Override @Override
public void fleeBattle() { public void fleeBattle() {
System.out.println("The troll calls for help!"); System.out.println("The troll calls for help!");
decorated.fleeBattle(); decorated.fleeBattle();
} }
} }

View File

@ -1,18 +1,18 @@
package com.iluwatar.decorator; package com.iluwatar.decorator;
/** /**
* *
* Troll implements Hostile interface directly. * Troll implements {@link Hostile} interface directly.
* *
*/ */
public class Troll implements Hostile { public class Troll implements Hostile {
public void attack() { public void attack() {
System.out.println("The troll swings at you with a club!"); System.out.println("The troll swings at you with a club!");
} }
public void fleeBattle() { public void fleeBattle() {
System.out.println("The troll shrieks in horror and runs away!"); System.out.println("The troll shrieks in horror and runs away!");
} }
} }

View File

@ -1,14 +1,19 @@
package com.iluwatar.decorator; package com.iluwatar.decorator;
import org.junit.Test; import org.junit.Test;
import com.iluwatar.decorator.App; import com.iluwatar.decorator.App;
public class AppTest { /**
*
@Test * Application test
public void test() { *
String[] args = {}; */
App.main(args); public class AppTest {
}
} @Test
public void test() {
String[] args = {};
App.main(args);
}
}

View File

@ -9,23 +9,27 @@ import com.google.inject.Injector;
* implements so called inversion of control principle. Inversion of control has two specific rules: * 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. * - 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. * - Abstractions should not depend on details. Details should depend on abstractions.
* * <p>
* In this example we show you three different wizards. The first one (SimpleWizard) is a naive * 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 violating the inversion of control principle. It depends directly on a concrete
* implementation which cannot be changed. * implementation which cannot be changed.
* * <p>
* The second wizard (AdvancedWizard) is more flexible. It does not depend on any concrete implementation * 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 Tobacco dependency to be * 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 * injected through its constructor. This way, handling the dependency is no longer the wizard's
* responsibility. It is resolved outside the wizard class. * responsibility. It is resolved outside the wizard class.
* * <p>
* The third example takes the pattern a step further. It uses Guice framework for Dependency Injection. * The third example takes the pattern a step further. It uses Guice framework for Dependency Injection.
* TobaccoModule binds a concrete implementation to abstraction. Injector is then used to create * {@link TobaccoModule} binds a concrete implementation to abstraction. Injector is then used to create
* GuiceWizard object with correct dependencies. * {@link GuiceWizard} object with correct dependencies.
* *
*/ */
public class App { public class App {
/**
* Program entry point
* @param args command line args
*/
public static void main( String[] args ) { public static void main( String[] args ) {
SimpleWizard simpleWizard = new SimpleWizard(); SimpleWizard simpleWizard = new SimpleWizard();
simpleWizard.smoke(); simpleWizard.smoke();

View File

@ -2,7 +2,7 @@ package com.iluwatar.dependency.injection;
/** /**
* *
* OldTobyTobacco concrete Tobacco implementation * OldTobyTobacco concrete {@link Tobacco} implementation
* *
*/ */
public class OldTobyTobacco extends Tobacco { public class OldTobyTobacco extends Tobacco {

View File

@ -2,7 +2,7 @@ package com.iluwatar.dependency.injection;
/** /**
* *
* RivendellTobacco concrete Tobacco implementation * RivendellTobacco concrete {@link Tobacco} implementation
* *
*/ */
public class RivendellTobacco extends Tobacco { public class RivendellTobacco extends Tobacco {

View File

@ -2,7 +2,7 @@ package com.iluwatar.dependency.injection;
/** /**
* *
* SecondBreakfastTobacco concrete Tobacco implementation * SecondBreakfastTobacco concrete {@link Tobacco} implementation
* *
*/ */
public class SecondBreakfastTobacco extends Tobacco { public class SecondBreakfastTobacco extends Tobacco {

View File

@ -4,7 +4,7 @@ import com.google.inject.AbstractModule;
/** /**
* *
* Guice module for binding certain concrete Tobacco implementation. * Guice module for binding certain concrete {@link Tobacco} implementation.
* *
*/ */
public class TobaccoModule extends AbstractModule { public class TobaccoModule extends AbstractModule {

View File

@ -4,6 +4,11 @@ import org.junit.Test;
import com.iluwatar.dependency.injection.App; import com.iluwatar.dependency.injection.App;
/**
*
* Application test
*
*/
public class AppTest { public class AppTest {
@Test @Test

View File

@ -5,13 +5,18 @@ import java.util.concurrent.Executors;
/** /**
* *
* In Inventory we store the items with a given size. However, we do not store * 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 * 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 * use double checked locking to add item to inventory. In this method, the
* thread which gets the lock first adds the item. * thread which gets the lock first adds the item.
*
*/ */
public class App { public class App {
/**
* Program entry point
* @param args command line args
*/
public static void main(String[] args) { public static void main(String[] args) {
final Inventory inventory = new Inventory(1000); final Inventory inventory = new Inventory(1000);
ExecutorService executorService = Executors.newFixedThreadPool(3); ExecutorService executorService = Executors.newFixedThreadPool(3);

View File

@ -5,6 +5,11 @@ import java.util.List;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
/**
*
* Inventory
*
*/
public class Inventory { public class Inventory {
private int inventorySize; private int inventorySize;

View File

@ -1,6 +1,12 @@
package com.iluwatar.doublechecked.locking; package com.iluwatar.doublechecked.locking;
/**
*
* Item
*
*/
public class Item { public class Item {
String name;
int level; private String name;
private int level;
} }

View File

@ -4,6 +4,11 @@ import org.junit.Test;
import com.iluwatar.doublechecked.locking.App; import com.iluwatar.doublechecked.locking.App;
/**
*
* Application test
*
*/
public class AppTest { public class AppTest {
@Test @Test

View File

@ -8,23 +8,27 @@ import java.util.List;
* When a message with a parameter is sent to an object, the resultant behaviour is defined by the * When a message with a parameter is sent to an object, the resultant behaviour is defined by the
* implementation of that method in the receiver. Sometimes the behaviour must also be determined * implementation of that method in the receiver. Sometimes the behaviour must also be determined
* by the type of the parameter. * by the type of the parameter.
* * <p>
* One way to implement this would be to create multiple instanceof-checks for the methods parameter. * 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 * 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 * 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. * principle - a class should have only one reason to change.
* * <p>
* Instead of the instanceof-checks a better way is to make another virtual call on the parameter * 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 * object. This way new functionality can be easily added without the need to modify existing
* implementation (open-closed principle). * implementation (open-closed principle).
* * <p>
* In this example we have hierarchy of objects (GameObject) that can collide to each other. Each * 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 * 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. * there is an overlap, then the objects collide utilizing the Double Dispatch pattern.
* *
*/ */
public class App { public class App {
/**
* Program entry point
* @param args command line args
*/
public static void main( String[] args ) { public static void main( String[] args ) {
// initialize game objects and print their status // initialize game objects and print their status
List<GameObject> objects = new ArrayList<>(); List<GameObject> objects = new ArrayList<>();

View File

@ -4,6 +4,11 @@ import org.junit.Test;
import com.iluwatar.doubledispatch.App; import com.iluwatar.doubledispatch.App;
/**
*
* Application test
*
*/
public class AppTest { public class AppTest {
@Test @Test

View File

@ -7,14 +7,18 @@ import java.util.List;
* *
* The Event Aggregator pattern channels events from multiple objects * The Event Aggregator pattern channels events from multiple objects
* into a single object to simplify registration for clients. * into a single object to simplify registration for clients.
* * <p>
* In the example LordBaelish, LordVarys and Scout deliver events to * In the example {@link LordBaelish}, {@link LordVarys} and {@link Scout} deliver events to
* KingsHand. KingsHand, the event aggregator, then delivers the events * {@link KingsHand}. {@link KingsHand}, the event aggregator, then delivers the events
* to KingJoffrey. * to {@link KingJoffrey}.
* *
*/ */
public class App { public class App {
/**
* Program entry point
* @param args command line args
*/
public static void main(String[] args) { public static void main(String[] args) {
KingJoffrey kingJoffrey = new KingJoffrey(); KingJoffrey kingJoffrey = new KingJoffrey();

View File

@ -2,7 +2,7 @@ package com.iluwatar.event.aggregator;
/** /**
* *
* KingJoffrey observes events from KingsHand. * KingJoffrey observes events from {@link KingsHand}.
* *
*/ */
public class KingJoffrey implements EventObserver { public class KingJoffrey implements EventObserver {

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