Formatted all files to the same standard

This commit is contained in:
matthew 2014-10-08 13:42:12 +01:00
parent 53a2a8b150
commit 3da9ad5469
151 changed files with 952 additions and 870 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.
*
*
*/
public class App {
public static void main(String[] args) {
createKingdom(new ElfKingdomFactory());
createKingdom(new OrcKingdomFactory());
}
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);
}
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

@ -6,5 +6,5 @@ public class ElfArmy implements Army {
public String toString() {
return "This is the Elven Army!";
}
}

View File

@ -6,5 +6,5 @@ public class ElfCastle implements Castle {
public String toString() {
return "This is the Elven castle!";
}
}

View File

@ -6,5 +6,5 @@ public class ElfKing implements King {
public String toString() {
return "This is the Elven king!";
}
}

View File

@ -3,7 +3,7 @@ package com.iluwatar;
/**
*
* Concrete factory.
*
*
*/
public class ElfKingdomFactory implements KingdomFactory {

View File

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

View File

@ -6,5 +6,5 @@ public class OrcArmy implements Army {
public String toString() {
return "This is the Orcish Army!";
}
}

View File

@ -6,5 +6,5 @@ public class OrcCastle implements Castle {
public String toString() {
return "This is the Orcish castle!";
}
}

View File

@ -6,5 +6,5 @@ public class OrcKing implements King {
public String toString() {
return "This is the Orc king!";
}
}

View File

@ -3,7 +3,7 @@ package com.iluwatar;
/**
*
* Concrete factory.
*
*
*/
public class OrcKingdomFactory implements KingdomFactory {

View File

@ -1,21 +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).
*
*
*/
public class App {
public static void main(String[] args) {
GnomeEngineeringManager manager = new GnomeEngineeringManager();
manager.operateDevice();
}
public static void main(String[] args) {
GnomeEngineeringManager manager = new GnomeEngineeringManager();
manager.operateDevice();
}
}

View File

@ -3,10 +3,10 @@ package com.iluwatar;
/**
*
* Engineers can operate devices.
*
*
*/
public interface Engineer {
void operateDevice();
}

View File

@ -2,15 +2,14 @@ package com.iluwatar;
/**
*
* Adapter class. Adapts the interface of the device
* (GoblinGlider) into Engineer interface expected
* by the client (GnomeEngineeringManager).
*
* Adapter class. Adapts the interface of the device (GoblinGlider) into
* Engineer interface expected by the client (GnomeEngineeringManager).
*
*/
public class GnomeEngineer implements Engineer {
private GoblinGlider glider;
public GnomeEngineer() {
glider = new GoblinGlider();
}
@ -21,5 +20,5 @@ public class GnomeEngineer implements Engineer {
glider.gainSpeed();
glider.takeOff();
}
}

View File

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

View File

@ -3,18 +3,18 @@ package com.iluwatar;
/**
*
* Device class (adaptee in the pattern).
*
*
*/
public class GoblinGlider {
public void attachGlider() {
System.out.println("Glider attached.");
}
public void gainSpeed() {
System.out.println("Gaining speed.");
}
public void takeOff() {
System.out.println("Lift-off!");
}

View File

@ -1,32 +1,35 @@
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.
*
*
*/
public class App {
public static void main(String[] args) {
BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(new Excalibur());
blindingMagicWeapon.wield();
blindingMagicWeapon.blind();
blindingMagicWeapon.swing();
blindingMagicWeapon.unwield();
public static void main(String[] args) {
BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(
new Excalibur());
blindingMagicWeapon.wield();
blindingMagicWeapon.blind();
blindingMagicWeapon.swing();
blindingMagicWeapon.unwield();
FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(new Mjollnir());
flyingMagicWeapon.wield();
flyingMagicWeapon.fly();
flyingMagicWeapon.swing();
flyingMagicWeapon.unwield();
FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(
new Mjollnir());
flyingMagicWeapon.wield();
flyingMagicWeapon.fly();
flyingMagicWeapon.swing();
flyingMagicWeapon.unwield();
SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(new Stormbringer());
soulEatingMagicWeapon.wield();
soulEatingMagicWeapon.swing();
soulEatingMagicWeapon.eatSoul();
soulEatingMagicWeapon.unwield();
SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(
new Stormbringer());
soulEatingMagicWeapon.wield();
soulEatingMagicWeapon.swing();
soulEatingMagicWeapon.eatSoul();
soulEatingMagicWeapon.unwield();
}
}
}

View File

@ -10,7 +10,7 @@ public class BlindingMagicWeapon extends MagicWeapon {
public BlindingMagicWeaponImp getImp() {
return (BlindingMagicWeaponImp) imp;
}
@Override
public void wield() {
getImp().wieldImp();
@ -29,5 +29,5 @@ public class BlindingMagicWeapon extends MagicWeapon {
public void blind() {
getImp().blindImp();
}
}

View File

@ -19,7 +19,8 @@ public class Excalibur extends BlindingMagicWeaponImp {
@Override
public void blindImp() {
System.out.println("bright light streams from Excalibur blinding the enemy");
System.out
.println("bright light streams from Excalibur blinding the enemy");
}
}

View File

@ -5,11 +5,11 @@ public class FlyingMagicWeapon extends MagicWeapon {
public FlyingMagicWeapon(FlyingMagicWeaponImp imp) {
super(imp);
}
public FlyingMagicWeaponImp getImp() {
return (FlyingMagicWeaponImp) imp;
}
@Override
public void wield() {
getImp().wieldImp();
@ -28,5 +28,5 @@ public class FlyingMagicWeapon extends MagicWeapon {
public void fly() {
getImp().flyImp();
}
}

View File

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

View File

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

View File

@ -19,7 +19,8 @@ public class Mjollnir extends FlyingMagicWeaponImp {
@Override
public void flyImp() {
System.out.println("Mjollnir hits the enemy in the air and returns back to the owner's hand");
System.out
.println("Mjollnir hits the enemy in the air and returns back to the owner's hand");
}
}

View File

@ -5,12 +5,12 @@ public class SoulEatingMagicWeapon extends MagicWeapon {
public SoulEatingMagicWeapon(SoulEatingMagicWeaponImp imp) {
super(imp);
}
@Override
public SoulEatingMagicWeaponImp getImp() {
return (SoulEatingMagicWeaponImp) imp;
}
@Override
public void wield() {
getImp().wieldImp();
@ -29,5 +29,5 @@ public class SoulEatingMagicWeapon extends MagicWeapon {
public void eatSoul() {
getImp().eatSoulImp();
}
}

View File

@ -3,5 +3,5 @@ package com.iluwatar;
public abstract class SoulEatingMagicWeaponImp extends MagicWeaponImp {
public abstract void eatSoulImp();
}

View File

@ -3,41 +3,36 @@ 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.
*
*
*/
public class App {
public static void main(String[] args) {
public static void main(String[] args) {
Hero mage = new HeroBuilder(Profession.MAGE, "Riobard")
.withHairColor(HairColor.BLACK)
.withWeapon(Weapon.DAGGER)
.build();
System.out.println(mage);
Hero mage = new HeroBuilder(Profession.MAGE, "Riobard")
.withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER)
.build();
System.out.println(mage);
Hero warrior = new HeroBuilder(Profession.WARRIOR, "Amberjill")
.withHairColor(HairColor.BLOND)
.withHairType(HairType.LONG_CURLY)
.withArmor(Armor.CHAIN_MAIL)
.withWeapon(Weapon.SWORD)
.build();
System.out.println(warrior);
Hero warrior = new HeroBuilder(Profession.WARRIOR, "Amberjill")
.withHairColor(HairColor.BLOND)
.withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL)
.withWeapon(Weapon.SWORD).build();
System.out.println(warrior);
Hero thief = new HeroBuilder(Profession.THIEF, "Desmond")
.withHairType(HairType.BALD)
.withWeapon(Weapon.BOW)
.build();
System.out.println(thief);
Hero thief = new HeroBuilder(Profession.THIEF, "Desmond")
.withHairType(HairType.BALD).withWeapon(Weapon.BOW).build();
System.out.println(thief);
}
}
}

View File

@ -3,17 +3,25 @@ package com.iluwatar;
public enum Armor {
CLOTHES, LEATHER, CHAIN_MAIL, PLATE_MAIL;
@Override
public String toString() {
String s = "";
switch(this) {
case CLOTHES: s = "clothes"; break;
case LEATHER: s = "leather armor"; break;
case CHAIN_MAIL: s = "chain mail"; break;
case PLATE_MAIL: s = "plate mail"; break;
switch (this) {
case CLOTHES:
s = "clothes";
break;
case LEATHER:
s = "leather armor";
break;
case CHAIN_MAIL:
s = "chain mail";
break;
case PLATE_MAIL:
s = "plate mail";
break;
}
return s;
}
}

View File

@ -3,18 +3,28 @@ package com.iluwatar;
public enum HairColor {
WHITE, BLOND, RED, BROWN, BLACK;
@Override
public String toString() {
String s = "";
switch(this) {
case WHITE: s = "white"; break;
case BLOND: s = "blond"; break;
case RED: s = "red"; break;
case BROWN: s = "brown"; break;
case BLACK: s = "black"; break;
switch (this) {
case WHITE:
s = "white";
break;
case BLOND:
s = "blond";
break;
case RED:
s = "red";
break;
case BROWN:
s = "brown";
break;
case BLACK:
s = "black";
break;
}
return s;
}
}

View File

@ -7,14 +7,24 @@ public enum HairType {
@Override
public String toString() {
String s = "";
switch(this) {
case BALD: s = "bold"; break;
case SHORT: s = "short"; break;
case CURLY: s = "curly"; break;
case LONG_STRAIGHT: s = "long straight"; break;
case LONG_CURLY: s = "long curly"; break;
switch (this) {
case BALD:
s = "bold";
break;
case SHORT:
s = "short";
break;
case CURLY:
s = "curly";
break;
case LONG_STRAIGHT:
s = "long straight";
break;
case LONG_CURLY:
s = "long curly";
break;
}
return s;
}
}

View File

@ -3,7 +3,7 @@ package com.iluwatar;
/**
*
* The class with many parameters.
*
*
*/
public class Hero {
@ -13,7 +13,7 @@ public class Hero {
private final HairColor hairColor;
private final Armor armor;
private final Weapon weapon;
public Profession getProfession() {
return profession;
}
@ -37,7 +37,7 @@ public class Hero {
public Weapon getWeapon() {
return weapon;
}
@Override
public String toString() {
@ -81,7 +81,7 @@ public class Hero {
/**
*
* The builder class.
*
*
*/
public static class HeroBuilder {
@ -91,20 +91,21 @@ public class Hero {
private HairColor hairColor;
private Armor armor;
private Weapon weapon;
public HeroBuilder(Profession profession, String name) {
if (profession == null || name == null) {
throw new NullPointerException("profession and name can not be null");
throw new NullPointerException(
"profession and name can not be null");
}
this.profession = profession;
this.name = name;
}
public HeroBuilder withHairType(HairType hairType) {
this.hairType = hairType;
return this;
}
public HeroBuilder withHairColor(HairColor hairColor) {
this.hairColor = hairColor;
return this;
@ -114,12 +115,12 @@ public class Hero {
this.armor = armor;
return this;
}
public HeroBuilder withWeapon(Weapon weapon) {
this.weapon = weapon;
return this;
}
public Hero build() {
return new Hero(this);
}

View File

@ -1,19 +1,27 @@
package com.iluwatar;
public enum Profession {
WARRIOR, THIEF, MAGE, PRIEST;
@Override
public String toString() {
String s = "";
switch(this) {
case WARRIOR: s = "Warrior"; break;
case THIEF: s = "Thief"; break;
case MAGE: s = "Mage"; break;
case PRIEST: s = "Priest"; break;
switch (this) {
case WARRIOR:
s = "Warrior";
break;
case THIEF:
s = "Thief";
break;
case MAGE:
s = "Mage";
break;
case PRIEST:
s = "Priest";
break;
}
return s;
}
}

View File

@ -3,18 +3,28 @@ package com.iluwatar;
public enum Weapon {
DAGGER, SWORD, AXE, WARHAMMER, BOW;
@Override
public String toString() {
String s = "";
switch(this) {
case DAGGER: s = "dagger"; break;
case SWORD: s = "sword"; break;
case AXE: s = "axe"; break;
case WARHAMMER: s = "warhammer"; break;
case BOW: s = "bow"; break;
switch (this) {
case DAGGER:
s = "dagger";
break;
case SWORD:
s = "sword";
break;
case AXE:
s = "axe";
break;
case WARHAMMER:
s = "warhammer";
break;
case BOW:
s = "bow";
break;
}
return s;
}
}

View File

@ -1,21 +1,22 @@
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.
*
*
*/
public class App {
public static void main(String[] args) {
public static void main(String[] args) {
OrcKing king = new OrcKing();
king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle"));
king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner"));
king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax"));
OrcKing king = new OrcKing();
king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle"));
king.makeRequest(new Request(RequestType.TORTURE_PRISONER,
"torture prisoner"));
king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax"));
}
}
}

View File

@ -5,7 +5,7 @@ public class OrcCommander extends RequestHandler {
public OrcCommander(RequestHandler handler) {
super(handler);
}
@Override
public void handleRequest(Request req) {
if (req.getRequestType().equals(RequestType.DEFEND_CASTLE)) {

View File

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

View File

@ -5,7 +5,7 @@ public class OrcOfficer extends RequestHandler {
public OrcOfficer(RequestHandler handler) {
super(handler);
}
@Override
public void handleRequest(Request req) {
if (req.getRequestType().equals(RequestType.TORTURE_PRISONER)) {

View File

@ -1,13 +1,13 @@
package com.iluwatar;
public abstract class RequestHandler {
private RequestHandler next;
public RequestHandler(RequestHandler next) {
this.next = next;
}
public void handleRequest(Request req) {
if (next != null) {
next.handleRequest(req);

View File

@ -2,8 +2,6 @@ package com.iluwatar;
public enum RequestType {
DEFEND_CASTLE,
TORTURE_PRISONER,
COLLECT_TAX
DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX
}

View File

@ -1,25 +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.
*
*
*/
public class App {
public static void main(String[] args) {
Wizard wizard = new Wizard();
Goblin goblin = new Goblin();
public static void main(String[] args) {
Wizard wizard = new Wizard();
Goblin goblin = new Goblin();
goblin.printStatus();
goblin.printStatus();
wizard.castSpell(new ShrinkSpell(), goblin);
goblin.printStatus();
wizard.castSpell(new ShrinkSpell(), goblin);
goblin.printStatus();
wizard.castSpell(new InvisibilitySpell(), goblin);
goblin.printStatus();
wizard.undoLastSpell();
goblin.printStatus();
}
wizard.castSpell(new InvisibilitySpell(), goblin);
goblin.printStatus();
wizard.undoLastSpell();
goblin.printStatus();
}
}

View File

@ -3,15 +3,15 @@ package com.iluwatar;
/**
*
* Interface for spells.
*
*
*/
public abstract class Command {
public abstract void execute(Target target);
public abstract void undo();
@Override
public abstract String toString();
public abstract String toString();
}

View File

@ -6,7 +6,7 @@ public class Goblin extends Target {
this.setSize(Size.NORMAL);
this.setVisibility(Visibility.VISIBLE);
}
@Override
public String toString() {
return "Goblin";

View File

@ -3,11 +3,11 @@ package com.iluwatar;
public class InvisibilitySpell extends Command {
private Target target;
public InvisibilitySpell() {
target = null;
}
@Override
public void execute(Target target) {
target.setVisibility(Visibility.INVISIBLE);

View File

@ -3,14 +3,14 @@ package com.iluwatar;
public class ShrinkSpell extends Command {
private Size oldSize;
private Target target;
public ShrinkSpell() {
oldSize = null;
target = null;
}
@Override
public void execute(Target target) {
oldSize = target.getSize();

View File

@ -2,15 +2,13 @@ package com.iluwatar;
public enum Size {
SMALL,
NORMAL,
LARGE;
SMALL, NORMAL, LARGE;
@Override
public String toString() {
String s = "";
switch (this) {
case LARGE:
s = "large";
@ -27,5 +25,4 @@ public enum Size {
return s;
}
}

View File

@ -5,7 +5,7 @@ public abstract class Target {
private Size size;
private Visibility visibility;
public Size getSize() {
return size;
}
@ -24,8 +24,9 @@ public abstract class Target {
@Override
public abstract String toString();
public void printStatus() {
System.out.println(String.format("%s, size=%s visibility=%s", this, getSize(), getVisibility()));
System.out.println(String.format("%s, size=%s visibility=%s", this,
getSize(), getVisibility()));
}
}

View File

@ -2,14 +2,13 @@ package com.iluwatar;
public enum Visibility {
VISIBLE,
INVISIBLE;
VISIBLE, INVISIBLE;
@Override
public String toString() {
String s = "";
switch (this) {
case INVISIBLE:
s = "invisible";
@ -19,7 +18,7 @@ public enum Visibility {
break;
default:
break;
}
return s;
}

View File

@ -3,13 +3,13 @@ package com.iluwatar;
public class Wizard extends Target {
private Command previousSpell;
public Wizard() {
this.setSize(Size.NORMAL);
this.setVisibility(Visibility.VISIBLE);
previousSpell = null;
}
public void castSpell(Command command, Target target) {
System.out.println(this + " casts " + command + " at " + target);
command.execute(target);
@ -22,10 +22,10 @@ public class Wizard extends Target {
previousSpell.undo();
}
}
@Override
public String toString() {
return "Wizard";
}
}

View File

@ -1,25 +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.
*
*
*/
public class App {
public static void main(String[] args) {
System.out.println("Message from the orcs: ");
public static void main(String[] args) {
System.out.println("Message from the orcs: ");
LetterComposite orcMessage = new Messenger().messageFromOrcs();
orcMessage.print();
LetterComposite orcMessage = new Messenger().messageFromOrcs();
orcMessage.print();
System.out.println("\n");
System.out.println("\n");
System.out.println("Message from the elves: ");
System.out.println("Message from the elves: ");
LetterComposite elfMessage = new Messenger().messageFromElves();
elfMessage.print();
}
LetterComposite elfMessage = new Messenger().messageFromElves();
elfMessage.print();
}
}

View File

@ -6,7 +6,7 @@ import java.util.List;
/**
*
* Composite interface.
*
*
*/
public abstract class LetterComposite {
@ -15,18 +15,18 @@ public abstract class LetterComposite {
public void add(LetterComposite letter) {
children.add(letter);
}
public int count() {
return children.size();
}
protected abstract void printThisBefore();
protected abstract void printThisAfter();
public void print() {
printThisBefore();
for (LetterComposite letter: children) {
for (LetterComposite letter : children) {
letter.print();
}
printThisAfter();

View File

@ -7,36 +7,47 @@ import java.util.List;
public class Messenger {
LetterComposite messageFromOrcs() {
List<Word> words = new ArrayList<Word>();
words.add(new Word(Arrays.asList(new Letter('W'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e'))));
words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e'))));
words.add(new Word(Arrays.asList(new Letter('W'), new Letter('h'),
new Letter('e'), new Letter('r'), new Letter('e'))));
words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'),
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('a'))));
words.add(new Word(Arrays.asList(new Letter('w'), new Letter('h'), new Letter('i'), new Letter('p'))));
words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e'))));
words.add(new Word(Arrays.asList(new Letter('w'), new Letter('h'),
new Letter('i'), new Letter('p'))));
words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'),
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('a'))));
words.add(new Word(Arrays.asList(new Letter('w'), new Letter('a'), new Letter('y'))));
words.add(new Word(Arrays.asList(new Letter('w'), new Letter('a'),
new Letter('y'))));
return new Sentence(words);
}
LetterComposite messageFromElves() {
List<Word> words = new ArrayList<Word>();
words.add(new Word(Arrays.asList(new Letter('M'), new Letter('u'), new Letter('c'), new Letter('h'))));
words.add(new Word(Arrays.asList(new Letter('w'), new Letter('i'), new Letter('n'), new Letter('d'))));
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('f'), new Letter('r'), new Letter('o'), new Letter('m'))));
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'))));
words.add(new Word(Arrays.asList(new Letter('M'), new Letter('u'),
new Letter('c'), new Letter('h'))));
words.add(new Word(Arrays.asList(new Letter('w'), new Letter('i'),
new Letter('n'), new Letter('d'))));
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('f'), new Letter('r'),
new Letter('o'), new Letter('m'))));
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

@ -5,11 +5,11 @@ import java.util.List;
public class Sentence extends LetterComposite {
public Sentence(List<Word> words) {
for (Word w: words) {
for (Word w : words) {
this.add(w);
}
}
@Override
protected void printThisBefore() {
// nop
@ -20,5 +20,4 @@ public class Sentence extends LetterComposite {
System.out.print(".");
}
}

View File

@ -5,11 +5,11 @@ import java.util.List;
public class Word extends LetterComposite {
public Word(List<Letter> letters) {
for (Letter l: letters) {
for (Letter l : letters) {
this.add(l);
}
}
@Override
protected void printThisBefore() {
System.out.print(" ");

View File

@ -1,24 +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
* "decorate" calls to the target.
*
*
*/
public class App {
public static void main(String[] args) {
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("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();
}
System.out.println("\nA smart looking troll surprises you.");
Hostile smart = new SmartTroll(new Troll());
smart.attack();
smart.fleeBattle();
}
}

View File

@ -3,6 +3,7 @@ package com.iluwatar;
public interface Hostile {
void attack();
void fleeBattle();
}

View File

@ -7,7 +7,7 @@ public class SmartTroll implements Hostile {
public SmartTroll(Hostile decorated) {
this.decorated = decorated;
}
@Override
public void attack() {
System.out.println("The troll throws a rock at you!");
@ -19,5 +19,5 @@ public class SmartTroll implements Hostile {
System.out.println("The troll calls for help!");
decorated.fleeBattle();
}
}

View File

@ -5,9 +5,9 @@ public class Troll implements Hostile {
public void attack() {
System.out.println("The troll swings at you with a club!");
}
public void fleeBattle() {
System.out.println("The troll shrieks in horror and runs away!");
}
}

View File

@ -4,7 +4,7 @@ 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
@ -12,16 +12,17 @@ import java.util.concurrent.Executors;
*/
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

@ -5,9 +5,8 @@ import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Inventory {
private int inventorySize;
private List<Item> items;
private Lock lock = new ReentrantLock();
@ -16,17 +15,17 @@ public class Inventory {
this.inventorySize = inventorySize;
this.items = new ArrayList<Item>(inventorySize);
}
public boolean addItem(Item item){
if(items.size()<inventorySize){
public boolean addItem(Item item) {
if (items.size() < inventorySize) {
lock.lock();
try{
if(items.size()<inventorySize){
try {
if (items.size() < inventorySize) {
items.add(item);
System.out.println(Thread.currentThread());
return true;
}
}finally{
} finally {
lock.unlock();
}
}

View File

@ -1,16 +1,16 @@
package com.iluwatar;
/**
*
*
* 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 static void main(String[] args) {
DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade();
facade.startNewDay();
facade.digOutGold();
facade.endDay();
}
}

View File

@ -6,32 +6,32 @@ import java.util.List;
public class DwarvenGoldmineFacade {
List<DwarvenMineWorker> workers;
public DwarvenGoldmineFacade() {
workers = new ArrayList<>();
workers.add(new DwarvenGoldDigger());
workers.add(new DwarvenCartOperator());
workers.add(new DwarvenTunnelDigger());
}
public void startNewDay() {
for (DwarvenMineWorker worker: workers) {
for (DwarvenMineWorker worker : workers) {
worker.wakeUp();
worker.goToMine();
}
}
public void digOutGold() {
for (DwarvenMineWorker worker: workers) {
for (DwarvenMineWorker worker : workers) {
worker.work();
}
}
public void endDay() {
for (DwarvenMineWorker worker: workers) {
for (DwarvenMineWorker worker : workers) {
worker.goHome();
worker.goToSleep();
}
}
}

View File

@ -5,21 +5,21 @@ public abstract class DwarvenMineWorker {
public void goToSleep() {
System.out.println(name() + " goes to sleep.");
}
public void wakeUp() {
System.out.println(name() + " wakes up.");
}
public void goHome() {
System.out.println(name() + " goes home.");
}
public void goToMine() {
System.out.println(name() + " goes to the mine.");
}
public abstract void work();
public abstract String name();
}

View File

@ -1,28 +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.
*
*
*/
public class App {
public static void main(String[] args) {
Blacksmith blacksmith;
Weapon weapon;
public static void main(String[] args) {
Blacksmith blacksmith;
Weapon weapon;
blacksmith = new OrcBlacksmith();
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
System.out.println(weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
System.out.println(weapon);
blacksmith = new OrcBlacksmith();
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
System.out.println(weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
System.out.println(weapon);
blacksmith = new ElfBlacksmith();
weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
System.out.println(weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
System.out.println(weapon);
}
blacksmith = new ElfBlacksmith();
weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
System.out.println(weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
System.out.println(weapon);
}
}

View File

@ -3,10 +3,10 @@ package com.iluwatar;
/**
*
* The interface containing method for producing objects.
*
*
*/
public interface Blacksmith {
Weapon manufactureWeapon(WeaponType weaponType);
}

View File

@ -3,7 +3,7 @@ package com.iluwatar;
/**
*
* Concrete subclass for creating new objects.
*
*
*/
public class ElfBlacksmith implements Blacksmith {

View File

@ -12,5 +12,5 @@ public class ElfWeapon implements Weapon {
public String toString() {
return "Elven " + weaponType;
}
}

View File

@ -3,7 +3,7 @@ package com.iluwatar;
/**
*
* Concrete subclass for creating new objects.
*
*
*/
public class OrcBlacksmith implements Blacksmith {

View File

@ -12,5 +12,5 @@ public class OrcWeapon implements Weapon {
public String toString() {
return "Orcish " + weaponType;
}
}

View File

@ -7,13 +7,18 @@ public enum WeaponType {
@Override
public String toString() {
String s = "";
switch(this) {
case SHORT_SWORD: s = "short sword"; break;
case SPEAR: s = "spear"; break;
case AXE: s = "axe"; break;
switch (this) {
case SHORT_SWORD:
s = "short sword";
break;
case SPEAR:
s = "spear";
break;
case AXE:
s = "axe";
break;
}
return s;
}
}

View File

@ -6,13 +6,13 @@ import java.util.List;
/**
*
* The class that needs many objects.
*
*
*/
public class AlchemistShop {
List<Potion> topShelf;
List<Potion> bottomShelf;
public AlchemistShop() {
topShelf = new ArrayList<>();
bottomShelf = new ArrayList<>();
@ -20,9 +20,9 @@ public class AlchemistShop {
}
private void fillShelves() {
PotionFactory factory = new PotionFactory();
topShelf.add(factory.createPotion(PotionType.INVISIBILITY));
topShelf.add(factory.createPotion(PotionType.INVISIBILITY));
topShelf.add(factory.createPotion(PotionType.STRENGTH));
@ -31,27 +31,27 @@ public class AlchemistShop {
topShelf.add(factory.createPotion(PotionType.STRENGTH));
topShelf.add(factory.createPotion(PotionType.HEALING));
topShelf.add(factory.createPotion(PotionType.HEALING));
bottomShelf.add(factory.createPotion(PotionType.POISON));
bottomShelf.add(factory.createPotion(PotionType.POISON));
bottomShelf.add(factory.createPotion(PotionType.POISON));
bottomShelf.add(factory.createPotion(PotionType.HOLY_WATER));
bottomShelf.add(factory.createPotion(PotionType.HOLY_WATER));
}
public void enumerate() {
System.out.println("Enumerating top shelf potions\n");
for (Potion p: topShelf) {
for (Potion p : topShelf) {
p.drink();
}
System.out.println("\nEnumerating bottom shelf potions\n");
for (Potion p: bottomShelf) {
for (Potion p : bottomShelf) {
p.drink();
}
}
}

View File

@ -1,16 +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.
*
*
*/
public class App {
public static void main(String[] args) {
AlchemistShop alchemistShop = new AlchemistShop();
alchemistShop.enumerate();
}
public static void main(String[] args) {
AlchemistShop alchemistShop = new AlchemistShop();
alchemistShop.enumerate();
}
}

View File

@ -4,7 +4,8 @@ public class HealingPotion implements Potion {
@Override
public void drink() {
System.out.println("You feel healed. (Potion=" + System.identityHashCode(this) + ")");
System.out.println("You feel healed. (Potion="
+ System.identityHashCode(this) + ")");
}
}

View File

@ -4,7 +4,8 @@ public class HolyWaterPotion implements Potion {
@Override
public void drink() {
System.out.println("You feel blessed. (Potion=" + System.identityHashCode(this) + ")");
System.out.println("You feel blessed. (Potion="
+ System.identityHashCode(this) + ")");
}
}

View File

@ -4,7 +4,8 @@ public class InvisibilityPotion implements Potion {
@Override
public void drink() {
System.out.println("You become invisible. (Potion=" + System.identityHashCode(this) + ")");
System.out.println("You become invisible. (Potion="
+ System.identityHashCode(this) + ")");
}
}

View File

@ -4,7 +4,8 @@ public class PoisonPotion implements Potion {
@Override
public void drink() {
System.out.println("Urgh! This is poisonous. (Potion=" + System.identityHashCode(this) + ")");
System.out.println("Urgh! This is poisonous. (Potion="
+ System.identityHashCode(this) + ")");
}
}

View File

@ -3,10 +3,10 @@ package com.iluwatar;
/**
*
* Interface for objects.
*
*
*/
public interface Potion {
public void drink();
}

View File

@ -5,16 +5,16 @@ import java.util.EnumMap;
/**
*
* Flyweight.
*
*
*/
public class PotionFactory {
private EnumMap<PotionType, Potion> potions;
public PotionFactory() {
potions = new EnumMap<>(PotionType.class);
}
Potion createPotion(PotionType type) {
Potion potion = potions.get(type);
if (potion == null) {
@ -45,5 +45,5 @@ public class PotionFactory {
}
return potion;
}
}

View File

@ -2,10 +2,6 @@ package com.iluwatar;
public enum PotionType {
HEALING,
INVISIBILITY,
STRENGTH,
HOLY_WATER,
POISON;
HEALING, INVISIBILITY, STRENGTH, HOLY_WATER, POISON;
}

View File

@ -4,7 +4,8 @@ public class StrengthPotion implements Potion {
@Override
public void drink() {
System.out.println("You feel strong. (Potion=" + System.identityHashCode(this) + ")");
System.out.println("You feel strong. (Potion="
+ System.identityHashCode(this) + ")");
}
}

View File

@ -3,64 +3,70 @@ 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.
*
*
*/
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<>();
/**
*
* 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()));
}
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 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 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

@ -3,7 +3,7 @@ package com.iluwatar;
public abstract class Expression {
public abstract int interpret();
@Override
public abstract String toString();
}

View File

@ -9,7 +9,7 @@ public class MinusExpression extends Expression {
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
}
@Override
public int interpret() {
return leftExpression.interpret() - rightExpression.interpret();

View File

@ -5,11 +5,12 @@ public class MultiplyExpression extends Expression {
private Expression leftExpression;
private Expression rightExpression;
public MultiplyExpression(Expression leftExpression, Expression rightExpression) {
public MultiplyExpression(Expression leftExpression,
Expression rightExpression) {
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
}
@Override
public int interpret() {
return leftExpression.interpret() * rightExpression.interpret();

View File

@ -7,11 +7,11 @@ public class NumberExpression extends Expression {
public NumberExpression(int number) {
this.number = number;
}
public NumberExpression(String s) {
this.number = Integer.parseInt(s);
}
@Override
public int interpret() {
return number;

View File

@ -9,7 +9,7 @@ public class PlusExpression extends Expression {
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
}
@Override
public int interpret() {
return leftExpression.interpret() + rightExpression.interpret();

View File

@ -1,41 +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.
*
*
*/
public class App {
public static void main(String[] args) {
TreasureChest chest = new TreasureChest();
public static void main(String[] args) {
TreasureChest chest = new TreasureChest();
ItemIterator ringIterator = chest.Iterator(ItemType.RING);
while (ringIterator.hasNext()) {
System.out.println(ringIterator.next());
}
ItemIterator ringIterator = chest.Iterator(ItemType.RING);
while (ringIterator.hasNext()) {
System.out.println(ringIterator.next());
}
System.out.println("----------");
System.out.println("----------");
ItemIterator potionIterator = chest.Iterator(ItemType.POTION);
while (potionIterator.hasNext()) {
System.out.println(potionIterator.next());
}
ItemIterator potionIterator = chest.Iterator(ItemType.POTION);
while (potionIterator.hasNext()) {
System.out.println(potionIterator.next());
}
System.out.println("----------");
System.out.println("----------");
ItemIterator weaponIterator = chest.Iterator(ItemType.WEAPON);
while (weaponIterator.hasNext()) {
System.out.println(weaponIterator.next());
}
ItemIterator weaponIterator = chest.Iterator(ItemType.WEAPON);
while (weaponIterator.hasNext()) {
System.out.println(weaponIterator.next());
}
System.out.println("----------");
System.out.println("----------");
ItemIterator it = chest.Iterator(ItemType.ANY);
while (it.hasNext()) {
System.out.println(it.next());
}
}
ItemIterator it = chest.Iterator(ItemType.ANY);
while (it.hasNext()) {
System.out.println(it.next());
}
}
}

View File

@ -9,7 +9,7 @@ public class Item {
this.setType(type);
this.name = name;
}
@Override
public String toString() {
return name;

View File

@ -3,11 +3,11 @@ package com.iluwatar;
/**
*
* Iterator interface.
*
*
*/
public interface ItemIterator {
boolean hasNext();
Item next();
}

View File

@ -2,9 +2,6 @@ package com.iluwatar;
public enum ItemType {
ANY,
WEAPON,
RING,
POTION
ANY, WEAPON, RING, POTION
}

View File

@ -6,12 +6,12 @@ import java.util.List;
/**
*
* Collection class.
*
*
*/
public class TreasureChest {
private List<Item> items;
public TreasureChest() {
items = new ArrayList<>();
items.add(new Item(ItemType.POTION, "Potion of courage"));
@ -25,7 +25,7 @@ public class TreasureChest {
items.add(new Item(ItemType.WEAPON, "Steel halberd"));
items.add(new Item(ItemType.WEAPON, "Dagger of poison"));
}
ItemIterator Iterator(ItemType type) {
return new TreasureChestItemIterator(this, type);
}
@ -35,5 +35,5 @@ public class TreasureChest {
list.addAll(items);
return list;
}
}

View File

@ -13,7 +13,7 @@ public class TreasureChestItemIterator implements ItemIterator {
this.type = type;
this.idx = -1;
}
@Override
public boolean hasNext() {
return findNextIdx() != -1;
@ -27,9 +27,9 @@ public class TreasureChestItemIterator implements ItemIterator {
}
return null;
}
private int findNextIdx() {
List<Item> items = chest.getItems();
boolean found = false;
int tempIdx = idx;
@ -39,7 +39,8 @@ public class TreasureChestItemIterator implements ItemIterator {
tempIdx = -1;
break;
}
if (type.equals(ItemType.ANY) || items.get(tempIdx).getType().equals(type)) {
if (type.equals(ItemType.ANY)
|| items.get(tempIdx).getType().equals(type)) {
break;
}
}

View File

@ -5,7 +5,7 @@ public enum Action {
HUNT, TALE, GOLD, ENEMY;
public String toString() {
String s = "";
switch (this) {
case ENEMY:

View File

@ -1,28 +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.
*
*
*/
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();
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);
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);
}
hobbit.act(Action.ENEMY);
wizard.act(Action.TALE);
rogue.act(Action.GOLD);
hunter.act(Action.HUNT);
}
}

View File

@ -3,12 +3,12 @@ package com.iluwatar;
/**
*
* Mediator interface.
*
*
*/
public interface Party {
void addMember(PartyMember member);
void act(PartyMember actor, Action action);
}

View File

@ -6,14 +6,14 @@ import java.util.List;
public class PartyImpl implements Party {
private List<PartyMember> members;
public PartyImpl() {
members = new ArrayList<>();
}
@Override
public void act(PartyMember actor, Action action) {
for (PartyMember member: members) {
for (PartyMember member : members) {
if (member != actor) {
member.partyAction(action);
}
@ -25,13 +25,13 @@ public class PartyImpl implements Party {
members.add(member);
member.joinedParty(this);
}
// somebody hunts for food, call for dinner
// somebody spots enemy, alert everybody
// somebody finds gold, deal the gold with everybody
// somebody tells a tale, call everybody to listen
}

View File

@ -3,12 +3,12 @@ package com.iluwatar;
/**
*
* Interface for party members interacting with Party.
*
*
*/
public interface PartyMember {
void joinedParty(Party party);
void partyAction(Action action);
void act(Action action);

View File

@ -31,7 +31,7 @@ public abstract class PartyMemberBase implements PartyMember {
}
System.out.println(s);
}
@Override
public void act(Action action) {
if (party != null) {
@ -42,5 +42,5 @@ public abstract class PartyMemberBase implements PartyMember {
@Override
public abstract String toString();
}

View File

@ -3,34 +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.
*
*
*/
public class App {
public static void main(String[] args) {
Stack<StarMemento> states = new Stack<>();
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);
}
}
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

@ -3,20 +3,20 @@ package com.iluwatar;
/**
*
* Star uses "mementos" to store and restore state.
*
*
*/
public class Star {
private StarType type;
private int ageYears;
private int massTons;
public Star(StarType startType, int startAge, int startMass) {
this.type = startType;
this.ageYears = startAge;
this.massTons = startMass;
}
public void timePasses() {
ageYears *= 2;
massTons *= 8;
@ -41,7 +41,7 @@ public class Star {
break;
}
}
StarMemento getMemento() {
StarMementoInternal state = new StarMementoInternal();
@ -49,20 +49,21 @@ public class Star {
state.setMassTons(massTons);
state.setType(type);
return state;
}
void setMemento(StarMemento memento) {
StarMementoInternal state = (StarMementoInternal) memento;
this.type = state.getType();
this.ageYears = state.getAgeYears();
this.massTons = state.getMassTons();
}
@Override
public String toString() {
return String.format("%s age: %d years mass: %d tons", type.toString(), ageYears, massTons);
return String.format("%s age: %d years mass: %d tons", type.toString(),
ageYears, massTons);
}
}

View File

@ -3,7 +3,7 @@ package com.iluwatar;
/**
*
* External interface to memento.
*
*
*/
public interface StarMemento {

View File

@ -3,29 +3,34 @@ package com.iluwatar;
/**
*
* Internal interface to memento.
*
*
*/
public class StarMementoInternal implements StarMemento {
private StarType type;
private int ageYears;
private int massTons;
public StarType getType() {
return type;
}
public void setType(StarType type) {
this.type = type;
}
public int getAgeYears() {
return ageYears;
}
public void setAgeYears(int ageYears) {
this.ageYears = ageYears;
}
public int getMassTons() {
return massTons;
}
public void setMassTons(int massTons) {
this.massTons = massTons;
}

View File

@ -2,11 +2,7 @@ package com.iluwatar;
public enum StarType {
SUN,
RED_GIANT,
WHITE_DWARF,
SUPERNOVA,
DEAD;
SUN, RED_GIANT, WHITE_DWARF, SUPERNOVA, DEAD;
@Override
public String toString() {
@ -32,5 +28,5 @@ public enum StarType {
}
return s;
}
}

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