Just formatting App classes to be like the other class files on the project

This commit is contained in:
Matthew 2014-10-07 16:23:37 +01:00
parent 52f0923df9
commit bde5b343d0
24 changed files with 466 additions and 508 deletions

View File

@ -1,29 +1,29 @@
package com.iluwatar;
/**
*
* The essence of the Abstract Factory pattern is a factory interface (KingdomFactory)
* and its implementations (ElfKingdomFactory, 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
* (KingdomFactory) and its implementations (ElfKingdomFactory,
* OrcKingdomFactory).
*
* The example uses both concrete implementations to create a king, a castle and
* an army.
*
*/
public class App
{
public static void main( String[] args )
{
createKingdom(new ElfKingdomFactory());
createKingdom(new OrcKingdomFactory());
public class App {
public static void main(String[] args) {
createKingdom(new ElfKingdomFactory());
createKingdom(new OrcKingdomFactory());
}
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);
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,23 +1,21 @@
package com.iluwatar;
/**
*
* 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 (GnomeEngineer) converts the interface of the
* target class (GoblinGlider) into a suitable one expected
* by the client (GnomeEngineeringManager).
*
* 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 (GnomeEngineer) converts the interface of the target class
* (GoblinGlider) into a suitable one expected by the client
* (GnomeEngineeringManager).
*
*/
public class App
{
public static void main( String[] args )
{
GnomeEngineeringManager manager = new GnomeEngineeringManager();
manager.operateDevice();
public class App {
public static void main(String[] args) {
GnomeEngineeringManager manager = new GnomeEngineeringManager();
manager.operateDevice();
}
}

View File

@ -1,35 +1,32 @@
package com.iluwatar;
/**
*
* In Bridge pattern both abstraction (MagicWeapon)
* and implementation (MagicWeaponImp) have their
* own class hierarchies. The interface of the
* implementations can be changed without affecting
* the clients.
*
* In Bridge pattern both abstraction (MagicWeapon) and implementation
* (MagicWeaponImp) have their own class hierarchies. The interface of the
* implementations can be changed without affecting the clients.
*
*/
public class App
{
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();
SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(new Stormbringer());
soulEatingMagicWeapon.wield();
soulEatingMagicWeapon.swing();
soulEatingMagicWeapon.eatSoul();
soulEatingMagicWeapon.unwield();
public class App {
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();
SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(new Stormbringer());
soulEatingMagicWeapon.wield();
soulEatingMagicWeapon.swing();
soulEatingMagicWeapon.eatSoul();
soulEatingMagicWeapon.unwield();
}
}

View File

@ -3,45 +3,41 @@ package com.iluwatar;
import com.iluwatar.Hero.HeroBuilder;
/**
*
* This is the Builder pattern variation as described by
* Joshua Bloch in Effective Java 2nd Edition.
*
* We want to build Hero objects, but its construction
* is complex because of the many parameters needed. To
* aid the user we introduce HeroBuilder class. HeroBuilder
* takes the minimum parameters to build Hero object in
* its constructor. After that additional configuration
* for the Hero object can be done using the fluent
* HeroBuilder interface. When configuration is ready
* the build method is called to receive the final Hero
* object.
*
* This is the Builder pattern variation as described by Joshua Bloch in
* Effective Java 2nd Edition.
*
* We want to build Hero objects, but its construction is complex because of the
* many parameters needed. To aid the user we introduce HeroBuilder class.
* HeroBuilder takes the minimum parameters to build Hero object in its
* constructor. After that additional configuration for the Hero object can be
* done using the fluent HeroBuilder interface. When configuration is ready the
* build method is called to receive the final Hero object.
*
*/
public class App
{
public static void main( String[] args )
{
Hero mage = new HeroBuilder(Profession.MAGE, "Riobard")
.withHairColor(HairColor.BLACK)
.withWeapon(Weapon.DAGGER)
.build();
System.out.println(mage);
public class App {
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);
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 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);
}
}

View File

@ -1,22 +1,21 @@
package com.iluwatar;
/**
*
* Chain of Responsibility organizes request handlers (RequestHandler) into
* a 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 (OrcCommander, OrcOfficer, OrcSoldier) form the handler chain.
*
* Chain of Responsibility organizes request handlers (RequestHandler) into a
* 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
* (OrcCommander, OrcOfficer, OrcSoldier) form the handler chain.
*
*/
public class App
{
public static void main( String[] args )
{
public class App {
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"));
}
}

View File

@ -1,27 +1,25 @@
package com.iluwatar;
/**
*
* In Command pattern actions are objects that can
* be executed and undone. The commands in this example
* are spells cast by the wizard on the goblin.
*
* In Command pattern actions are objects that can be executed and undone. The
* commands in this example are spells cast by the wizard on the goblin.
*
*/
public class App
{
public static void main( String[] args )
{
Wizard wizard = new Wizard();
Goblin goblin = new Goblin();
public class App {
goblin.printStatus();
wizard.castSpell(new ShrinkSpell(), goblin);
goblin.printStatus();
wizard.castSpell(new InvisibilitySpell(), goblin);
goblin.printStatus();
wizard.undoLastSpell();
goblin.printStatus();
public static void main(String[] args) {
Wizard wizard = new Wizard();
Goblin goblin = new Goblin();
goblin.printStatus();
wizard.castSpell(new ShrinkSpell(), goblin);
goblin.printStatus();
wizard.castSpell(new InvisibilitySpell(), goblin);
goblin.printStatus();
wizard.undoLastSpell();
goblin.printStatus();
}
}

View File

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

View File

@ -1,26 +1,24 @@
package com.iluwatar;
/**
*
* Decorator pattern is more flexible alternative to
* subclassing. The decorator class implements the same
* interface as the target and uses composition to
*
* Decorator pattern is more flexible alternative to subclassing. The decorator
* class implements the same interface as the target and uses composition to
* "decorate" calls to the target.
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println("A simple looking troll approaches.");
Hostile troll = new Troll();
troll.attack();
troll.fleeBattle();
System.out.println("\nA smart looking troll surprises you.");
Hostile smart = new SmartTroll(new Troll());
smart.attack();
smart.fleeBattle();
public class App {
public static void main(String[] args) {
System.out.println("A simple looking troll approaches.");
Hostile troll = new Troll();
troll.attack();
troll.fleeBattle();
System.out.println("\nA smart looking troll surprises you.");
Hostile smart = new SmartTroll(new Troll());
smart.attack();
smart.fleeBattle();
}
}

View File

@ -4,27 +4,24 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
*
* In 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 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 {
public class App
{
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(new Runnable() {
@Override
public void run() {
while(inventory.addItem(new Item()));
}
});
}
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(new Runnable() {
@Override
public void run() {
while (inventory.addItem(new Item()));
}
});
}
}
}

View File

@ -1,18 +1,16 @@
package com.iluwatar;
/**
*
* Facade (DwarvenGoldmineFacade) provides simpler interface to
* subsystem.
*
* Facade (DwarvenGoldmineFacade) provides simpler interface to subsystem.
*
*/
public class App
{
public static void main( String[] args )
{
DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade();
facade.startNewDay();
facade.digOutGold();
facade.endDay();
public class App {
public static void main(String[] args) {
DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade();
facade.startNewDay();
facade.digOutGold();
facade.endDay();
}
}

View File

@ -1,30 +1,28 @@
package com.iluwatar;
/**
*
* In Factory Method we have an interface (Blacksmith) with a
* method for creating objects (manufactureWeapon). The concrete
* subclasses (OrcBlacksmith, ElfBlacksmith) then override the
* method to produce objects of their liking.
*
* In Factory Method we have an interface (Blacksmith) with a method for
* creating objects (manufactureWeapon). The concrete subclasses (OrcBlacksmith,
* ElfBlacksmith) then override the method to produce objects of their liking.
*
*/
public class App
{
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 ElfBlacksmith();
weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
System.out.println(weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
System.out.println(weapon);
public class App {
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 ElfBlacksmith();
weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
System.out.println(weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
System.out.println(weapon);
}
}

View File

@ -1,17 +1,16 @@
package com.iluwatar;
/**
*
* Flyweight (PotionFactory) is useful when there is plethora of
* objects (Potion). It provides means to decrease resource usage
* by sharing object instances.
*
* Flyweight (PotionFactory) is useful when there is plethora of objects
* (Potion). It provides means to decrease resource usage by sharing object
* instances.
*
*/
public class App
{
public static void main( String[] args )
{
AlchemistShop alchemistShop = new AlchemistShop();
alchemistShop.enumerate();
public class App {
public static void main(String[] args) {
AlchemistShop alchemistShop = new AlchemistShop();
alchemistShop.enumerate();
}
}

View File

@ -3,65 +3,64 @@ package com.iluwatar;
import java.util.Stack;
/**
*
* Interpreter pattern breaks sentences into expressions (Expression)
* that can be evaluated and as a whole form the result.
*
* Interpreter pattern breaks sentences into expressions (Expression) that can
* be evaluated and as a whole form the result.
*
*/
public class App
{
/**
*
* Expressions can be evaluated using prefix, infix or postfix notations
* This sample uses postfix, where operator comes after the operands
*
*/
public static void main( String[] args )
{
String tokenString = "4 3 2 - 1 + *";
Stack<Expression> stack = new Stack<>();
public class App {
String[] tokenList = tokenString.split(" ");
for (String s : tokenList) {
if (isOperator(s)) {
Expression rightExpression = stack.pop();
Expression leftExpression = stack.pop();
System.out.println(String.format("popped from stack left: %d right: %d",
leftExpression.interpret(), rightExpression.interpret()));
Expression operator = getOperatorInstance(s, leftExpression,
rightExpression);
System.out.println(String.format("operator: %s", operator));
int result = operator.interpret();
NumberExpression resultExpression = new NumberExpression(result);
stack.push(resultExpression);
System.out.println(String.format("push result to stack: %d", resultExpression.interpret()));
} else {
Expression i = new NumberExpression(s);
stack.push(i);
System.out.println(String.format("push to stack: %d", i.interpret()));
}
}
System.out.println(String.format("result: %d", stack.pop().interpret()));
/**
*
* Expressions can be evaluated using prefix, infix or postfix notations
* This sample uses postfix, where operator comes after the operands
*
*/
public static void main(String[] args) {
String tokenString = "4 3 2 - 1 + *";
Stack<Expression> stack = new Stack<>();
String[] tokenList = tokenString.split(" ");
for (String s : tokenList) {
if (isOperator(s)) {
Expression rightExpression = stack.pop();
Expression leftExpression = stack.pop();
System.out.println(String.format("popped from stack left: %d right: %d",
leftExpression.interpret(), rightExpression.interpret()));
Expression operator = getOperatorInstance(s, leftExpression,
rightExpression);
System.out.println(String.format("operator: %s", operator));
int result = operator.interpret();
NumberExpression resultExpression = new NumberExpression(result);
stack.push(resultExpression);
System.out.println(String.format("push result to stack: %d", resultExpression.interpret()));
} else {
Expression i = new NumberExpression(s);
stack.push(i);
System.out.println(String.format("push to stack: %d", i.interpret()));
}
}
System.out.println(String.format("result: %d", stack.pop().interpret()));
}
public static boolean isOperator(String s) {
if (s.equals("+") || s.equals("-") || s.equals("*"))
return true;
else
return false;
}
public static Expression getOperatorInstance(String s, Expression left,
Expression right) {
switch (s) {
case "+":
return new PlusExpression(left, right);
case "-":
return new MinusExpression(left, right);
case "*":
return new MultiplyExpression(left, right);
}
return null;
}
public static boolean isOperator(String s) {
if (s.equals("+") || s.equals("-") || s.equals("*")) {
return true;
} else {
return false;
}
}
public static Expression getOperatorInstance(String s, Expression left,
Expression right) {
switch (s) {
case "+":
return new PlusExpression(left, right);
case "-":
return new MinusExpression(left, right);
case "*":
return new MultiplyExpression(left, right);
}
return null;
}
}

View File

@ -1,42 +1,41 @@
package com.iluwatar;
/**
*
* Iterator (ItemIterator) adds abstraction layer on top of a
* collection (TreasureChest). This way the collection can change
* its internal implementation without affecting its clients.
*
* Iterator (ItemIterator) adds abstraction layer on top of a collection
* (TreasureChest). This way the collection can change its internal
* implementation without affecting its clients.
*
*/
public class App
{
public static void main( String[] args )
{
TreasureChest chest = new TreasureChest();
ItemIterator ringIterator = chest.Iterator(ItemType.RING);
while (ringIterator.hasNext()) {
System.out.println(ringIterator.next());
}
System.out.println("----------");
ItemIterator potionIterator = chest.Iterator(ItemType.POTION);
while (potionIterator.hasNext()) {
System.out.println(potionIterator.next());
}
System.out.println("----------");
ItemIterator weaponIterator = chest.Iterator(ItemType.WEAPON);
while (weaponIterator.hasNext()) {
System.out.println(weaponIterator.next());
}
System.out.println("----------");
ItemIterator it = chest.Iterator(ItemType.ANY);
while (it.hasNext()) {
System.out.println(it.next());
}
public class App {
public static void main(String[] args) {
TreasureChest chest = new TreasureChest();
ItemIterator ringIterator = chest.Iterator(ItemType.RING);
while (ringIterator.hasNext()) {
System.out.println(ringIterator.next());
}
System.out.println("----------");
ItemIterator potionIterator = chest.Iterator(ItemType.POTION);
while (potionIterator.hasNext()) {
System.out.println(potionIterator.next());
}
System.out.println("----------");
ItemIterator weaponIterator = chest.Iterator(ItemType.WEAPON);
while (weaponIterator.hasNext()) {
System.out.println(weaponIterator.next());
}
System.out.println("----------");
ItemIterator it = chest.Iterator(ItemType.ANY);
while (it.hasNext()) {
System.out.println(it.next());
}
}
}

View File

@ -1,30 +1,28 @@
package com.iluwatar;
/**
*
* Mediator encapsulates how set of objects (PartyMember) interact.
* Instead of referring to each other directly they
* use the mediator (Party) interface.
*
* Mediator encapsulates how set of objects (PartyMember) interact. Instead of
* referring to each other directly they use the mediator (Party) interface.
*
*/
public class App
{
public static void main( String[] args )
{
Party party = new PartyImpl();
Hobbit hobbit = new Hobbit();
Wizard wizard = new Wizard();
Rogue rogue = new Rogue();
Hunter hunter = new Hunter();
party.addMember(hobbit);
party.addMember(wizard);
party.addMember(rogue);
party.addMember(hunter);
hobbit.act(Action.ENEMY);
wizard.act(Action.TALE);
rogue.act(Action.GOLD);
hunter.act(Action.HUNT);
public class App {
public static void main(String[] args) {
Party party = new PartyImpl();
Hobbit hobbit = new Hobbit();
Wizard wizard = new Wizard();
Rogue rogue = new Rogue();
Hunter hunter = new Hunter();
party.addMember(hobbit);
party.addMember(wizard);
party.addMember(rogue);
party.addMember(hunter);
hobbit.act(Action.ENEMY);
wizard.act(Action.TALE);
rogue.act(Action.GOLD);
hunter.act(Action.HUNT);
}
}

View File

@ -3,37 +3,34 @@ package com.iluwatar;
import java.util.Stack;
/**
*
* Memento pattern is for storing and restoring object
* state. The object (Star) gives out a "memento"
* (StarMemento) that contains the state of the object.
* Later on the memento can be set back to the object
* restoring the state.
*
* Memento pattern is for storing and restoring object state. The object (Star)
* gives out a "memento" (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<StarMemento> states = new Stack<>();
Star star = new Star(StarType.SUN, 10000000, 500000);
System.out.println(star);
states.add(star.getMemento());
star.timePasses();
System.out.println(star);
states.add(star.getMemento());
star.timePasses();
System.out.println(star);
states.add(star.getMemento());
star.timePasses();
System.out.println(star);
states.add(star.getMemento());
star.timePasses();
System.out.println(star);
while (states.size() > 0) {
star.setMemento(states.pop());
System.out.println(star);
}
public class App {
public static void main(String[] args) {
Stack<StarMemento> states = new Stack<>();
Star star = new Star(StarType.SUN, 10000000, 500000);
System.out.println(star);
states.add(star.getMemento());
star.timePasses();
System.out.println(star);
states.add(star.getMemento());
star.timePasses();
System.out.println(star);
states.add(star.getMemento());
star.timePasses();
System.out.println(star);
states.add(star.getMemento());
star.timePasses();
System.out.println(star);
while (states.size() > 0) {
star.setMemento(states.pop());
System.out.println(star);
}
}
}

View File

@ -1,25 +1,23 @@
package com.iluwatar;
/**
*
* Observer pattern defines one-to-many relationship
* between objects. The target object sends change
* notifications to its registered observers.
*
* Observer pattern defines one-to-many relationship between objects. The target
* object sends change notifications to its registered observers.
*
*/
public class App
{
public static void main( String[] args )
{
public class App {
public static void main(String[] args) {
Weather weather = new Weather();
weather.addObserver(new Orcs());
weather.addObserver(new Hobbits());
weather.timePasses();
weather.timePasses();
weather.timePasses();
weather.timePasses();
Weather weather = new Weather();
weather.addObserver(new Orcs());
weather.addObserver(new Hobbits());
weather.timePasses();
weather.timePasses();
weather.timePasses();
weather.timePasses();
}
}

View File

@ -1,35 +1,34 @@
package com.iluwatar;
/**
*
* In Prototype we have a factory class (HeroFactoryImpl) producing
* objects by cloning existing ones. In this example the factory's
* prototype objects are given as constructor parameters.
*
* In Prototype we have a factory class (HeroFactoryImpl) producing objects by
* cloning existing ones. In this example the factory's prototype objects are
* given as constructor parameters.
*
*/
public class App
{
public static void main( String[] args )
{
HeroFactory factory;
Mage mage;
Warlord warlord;
Beast beast;
factory = new HeroFactoryImpl(new ElfMage(), new ElfWarlord(), new ElfBeast());
mage = factory.createMage();
warlord = factory.createWarlord();
beast = factory.createBeast();
System.out.println(mage);
System.out.println(warlord);
System.out.println(beast);
factory = new HeroFactoryImpl(new OrcMage(), new OrcWarlord(), new OrcBeast());
mage = factory.createMage();
warlord = factory.createWarlord();
beast = factory.createBeast();
System.out.println(mage);
System.out.println(warlord);
System.out.println(beast);
public class App {
public static void main(String[] args) {
HeroFactory factory;
Mage mage;
Warlord warlord;
Beast beast;
factory = new HeroFactoryImpl(new ElfMage(), new ElfWarlord(), new ElfBeast());
mage = factory.createMage();
warlord = factory.createWarlord();
beast = factory.createBeast();
System.out.println(mage);
System.out.println(warlord);
System.out.println(beast);
factory = new HeroFactoryImpl(new OrcMage(), new OrcWarlord(), new OrcBeast());
mage = factory.createMage();
warlord = factory.createWarlord();
beast = factory.createBeast();
System.out.println(mage);
System.out.println(warlord);
System.out.println(beast);
}
}

View File

@ -1,22 +1,20 @@
package com.iluwatar;
/**
*
* Proxy (WizardTowerProxy) controls access to the
* actual object (WizardTower).
*
* Proxy (WizardTowerProxy) controls access to the actual object (WizardTower).
*
*/
public class App
{
public static void main( String[] args )
{
public class App {
public static void main(String[] args) {
WizardTowerProxy tower = new WizardTowerProxy();
tower.enter(new Wizard("Red wizard"));
tower.enter(new Wizard("White wizard"));
tower.enter(new Wizard("Black wizard"));
tower.enter(new Wizard("Green wizard"));
tower.enter(new Wizard("Brown wizard"));
WizardTowerProxy tower = new WizardTowerProxy();
tower.enter(new Wizard("Red wizard"));
tower.enter(new Wizard("White wizard"));
tower.enter(new Wizard("Black wizard"));
tower.enter(new Wizard("Green wizard"));
tower.enter(new Wizard("Brown wizard"));
}
}

View File

@ -1,20 +1,19 @@
package com.iluwatar;
/**
*
* Singleton pattern ensures that the class (IvoryTower) can have only
* one existing instance and provides global access to that instance.
*
* Singleton pattern ensures that the class (IvoryTower) can have only one
* existing instance and provides global access to that instance.
*
*/
public class App
{
public static void main( String[] args )
{
IvoryTower ivoryTower1 = IvoryTower.getInstance();
IvoryTower ivoryTower2 = IvoryTower.getInstance();
System.out.println("ivoryTower1=" + ivoryTower1);
System.out.println("ivoryTower2=" + ivoryTower2);
public class App {
public static void main(String[] args) {
IvoryTower ivoryTower1 = IvoryTower.getInstance();
IvoryTower ivoryTower2 = IvoryTower.getInstance();
System.out.println("ivoryTower1=" + ivoryTower1);
System.out.println("ivoryTower2=" + ivoryTower2);
}
}

View File

@ -1,24 +1,22 @@
package com.iluwatar;
/**
*
* In State pattern the object (Mammoth) has internal
* state object (State) that defines the current
* behavior. The state object can be changed
* to alter the behavior.
*
* In State pattern the object (Mammoth) has internal state object (State) that
* defines the current behavior. The state object can be changed to alter the
* behavior.
*
*/
public class App
{
public static void main( String[] args )
{
public class App {
public static void main(String[] args) {
Mammoth mammoth = new Mammoth();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
Mammoth mammoth = new Mammoth();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
}
}

View File

@ -1,23 +1,22 @@
package com.iluwatar;
/**
*
* Strategy (DragonSlayingStrategy) encapsulates the algorithm to use.
* The object (DragonSlayer) can alter its behavior by changing its strategy.
*
* Strategy (DragonSlayingStrategy) encapsulates the algorithm to use. The
* object (DragonSlayer) can alter its behavior by changing its strategy.
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println("Green dragon spotted ahead!");
DragonSlayer dragonSlayer = new DragonSlayer(new MeleeStrategy());
dragonSlayer.goToBattle();
System.out.println("Red dragon emerges.");
dragonSlayer.changeStrategy(new ProjectileStrategy());
dragonSlayer.goToBattle();
System.out.println("Black dragon lands before you.");
dragonSlayer.changeStrategy(new SpellStrategy());
dragonSlayer.goToBattle();
public class App {
public static void main(String[] args) {
System.out.println("Green dragon spotted ahead!");
DragonSlayer dragonSlayer = new DragonSlayer(new MeleeStrategy());
dragonSlayer.goToBattle();
System.out.println("Red dragon emerges.");
dragonSlayer.changeStrategy(new ProjectileStrategy());
dragonSlayer.goToBattle();
System.out.println("Black dragon lands before you.");
dragonSlayer.changeStrategy(new SpellStrategy());
dragonSlayer.goToBattle();
}
}

View File

@ -1,19 +1,17 @@
package com.iluwatar;
/**
*
* Template Method (StealingMethod) defines skeleton for the
* algorithm and subclasses (HitAndRunMethod, SubtleMethod)
* fill in the blanks.
*
* Template Method (StealingMethod) defines skeleton for the algorithm and
* subclasses (HitAndRunMethod, SubtleMethod) fill in the blanks.
*
*/
public class App
{
public static void main( String[] args )
{
HalflingThief thief = new HalflingThief(new HitAndRunMethod());
thief.steal();
thief.changeMethod(new SubtleMethod());
thief.steal();
public class App {
public static void main(String[] args) {
HalflingThief thief = new HalflingThief(new HitAndRunMethod());
thief.steal();
thief.changeMethod(new SubtleMethod());
thief.steal();
}
}

View File

@ -1,23 +1,22 @@
package com.iluwatar;
/**
*
* Visitor pattern defines mechanism to apply operations
* (UnitVisitor) on nodes (Unit) in hierarchy. New operations
* can be added without altering the node interface.
*
* Visitor pattern defines mechanism to apply operations (UnitVisitor) on nodes
* (Unit) in hierarchy. New operations can be added without altering the node
* interface.
*
*/
public class App
{
public static void main( String[] args )
{
public class App {
public static void main(String[] args) {
Commander commander = new Commander(
new Sergeant(new Soldier(), new Soldier(), new Soldier()),
new Sergeant(new Soldier(), new Soldier(), new Soldier()));
commander.accept(new SoldierVisitor());
commander.accept(new SergeantVisitor());
commander.accept(new CommanderVisitor());
Commander commander = new Commander(
new Sergeant(new Soldier(), new Soldier(), new Soldier()),
new Sergeant(new Soldier(), new Soldier(), new Soldier()));
commander.accept(new SoldierVisitor());
commander.accept(new SergeantVisitor());
commander.accept(new CommanderVisitor());
}
}