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

@ -12,18 +12,18 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
createKingdom(new ElfKingdomFactory()); createKingdom(new ElfKingdomFactory());
createKingdom(new OrcKingdomFactory()); createKingdom(new OrcKingdomFactory());
} }
public static void createKingdom(KingdomFactory factory) { public static void createKingdom(KingdomFactory factory) {
King king = factory.createKing(); King king = factory.createKing();
Castle castle = factory.createCastle(); Castle castle = factory.createCastle();
Army army = factory.createArmy(); Army army = factory.createArmy();
System.out.println("The kingdom was created."); System.out.println("The kingdom was created.");
System.out.println(king); System.out.println(king);
System.out.println(castle); System.out.println(castle);
System.out.println(army); System.out.println(army);
} }
} }

View File

@ -8,7 +8,9 @@ package com.iluwatar;
public interface KingdomFactory { public interface KingdomFactory {
Castle createCastle(); Castle createCastle();
King createKing(); King createKing();
Army createArmy(); Army createArmy();
} }

View File

@ -14,8 +14,8 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
GnomeEngineeringManager manager = new GnomeEngineeringManager(); GnomeEngineeringManager manager = new GnomeEngineeringManager();
manager.operateDevice(); manager.operateDevice();
} }
} }

View File

@ -2,9 +2,8 @@ package com.iluwatar;
/** /**
* *
* Adapter class. Adapts the interface of the device * Adapter class. Adapts the interface of the device (GoblinGlider) into
* (GoblinGlider) into Engineer interface expected * Engineer interface expected by the client (GnomeEngineeringManager).
* by the client (GnomeEngineeringManager).
* *
*/ */
public class GnomeEngineer implements Engineer { public class GnomeEngineer implements Engineer {

View File

@ -2,8 +2,7 @@ package com.iluwatar;
/** /**
* *
* GnomeEngineering manager uses Engineer to * GnomeEngineering manager uses Engineer to operate devices.
* operate devices.
* *
*/ */
public class GnomeEngineeringManager implements Engineer { public class GnomeEngineeringManager implements Engineer {

View File

@ -9,24 +9,27 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(new Excalibur()); BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(
blindingMagicWeapon.wield(); new Excalibur());
blindingMagicWeapon.blind(); blindingMagicWeapon.wield();
blindingMagicWeapon.swing(); blindingMagicWeapon.blind();
blindingMagicWeapon.unwield(); blindingMagicWeapon.swing();
blindingMagicWeapon.unwield();
FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(new Mjollnir()); FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(
flyingMagicWeapon.wield(); new Mjollnir());
flyingMagicWeapon.fly(); flyingMagicWeapon.wield();
flyingMagicWeapon.swing(); flyingMagicWeapon.fly();
flyingMagicWeapon.unwield(); flyingMagicWeapon.swing();
flyingMagicWeapon.unwield();
SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(new Stormbringer()); SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(
soulEatingMagicWeapon.wield(); new Stormbringer());
soulEatingMagicWeapon.swing(); soulEatingMagicWeapon.wield();
soulEatingMagicWeapon.eatSoul(); soulEatingMagicWeapon.swing();
soulEatingMagicWeapon.unwield(); soulEatingMagicWeapon.eatSoul();
soulEatingMagicWeapon.unwield();
} }
} }

View File

@ -19,7 +19,8 @@ public class Excalibur extends BlindingMagicWeaponImp {
@Override @Override
public void blindImp() { 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

@ -19,7 +19,8 @@ public class Mjollnir extends FlyingMagicWeaponImp {
@Override @Override
public void flyImp() { 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

@ -17,27 +17,22 @@ import com.iluwatar.Hero.HeroBuilder;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
Hero mage = new HeroBuilder(Profession.MAGE, "Riobard") Hero mage = new HeroBuilder(Profession.MAGE, "Riobard")
.withHairColor(HairColor.BLACK) .withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER)
.withWeapon(Weapon.DAGGER) .build();
.build(); System.out.println(mage);
System.out.println(mage);
Hero warrior = new HeroBuilder(Profession.WARRIOR, "Amberjill") Hero warrior = new HeroBuilder(Profession.WARRIOR, "Amberjill")
.withHairColor(HairColor.BLOND) .withHairColor(HairColor.BLOND)
.withHairType(HairType.LONG_CURLY) .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL)
.withArmor(Armor.CHAIN_MAIL) .withWeapon(Weapon.SWORD).build();
.withWeapon(Weapon.SWORD) System.out.println(warrior);
.build();
System.out.println(warrior);
Hero thief = new HeroBuilder(Profession.THIEF, "Desmond") Hero thief = new HeroBuilder(Profession.THIEF, "Desmond")
.withHairType(HairType.BALD) .withHairType(HairType.BALD).withWeapon(Weapon.BOW).build();
.withWeapon(Weapon.BOW) System.out.println(thief);
.build();
System.out.println(thief);
} }
} }

View File

@ -7,11 +7,19 @@ public enum Armor {
@Override @Override
public String toString() { public String toString() {
String s = ""; String s = "";
switch(this) { switch (this) {
case CLOTHES: s = "clothes"; break; case CLOTHES:
case LEATHER: s = "leather armor"; break; s = "clothes";
case CHAIN_MAIL: s = "chain mail"; break; break;
case PLATE_MAIL: s = "plate mail"; break; case LEATHER:
s = "leather armor";
break;
case CHAIN_MAIL:
s = "chain mail";
break;
case PLATE_MAIL:
s = "plate mail";
break;
} }
return s; return s;
} }

View File

@ -7,12 +7,22 @@ public enum HairColor {
@Override @Override
public String toString() { public String toString() {
String s = ""; String s = "";
switch(this) { switch (this) {
case WHITE: s = "white"; break; case WHITE:
case BLOND: s = "blond"; break; s = "white";
case RED: s = "red"; break; break;
case BROWN: s = "brown"; break; case BLOND:
case BLACK: s = "black"; break; s = "blond";
break;
case RED:
s = "red";
break;
case BROWN:
s = "brown";
break;
case BLACK:
s = "black";
break;
} }
return s; return s;
} }

View File

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

View File

@ -94,7 +94,8 @@ public class Hero {
public HeroBuilder(Profession profession, String name) { public HeroBuilder(Profession profession, String name) {
if (profession == null || name == null) { 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.profession = profession;
this.name = name; this.name = name;

View File

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

View File

@ -7,12 +7,22 @@ public enum Weapon {
@Override @Override
public String toString() { public String toString() {
String s = ""; String s = "";
switch(this) { switch (this) {
case DAGGER: s = "dagger"; break; case DAGGER:
case SWORD: s = "sword"; break; s = "dagger";
case AXE: s = "axe"; break; break;
case WARHAMMER: s = "warhammer"; break; case SWORD:
case BOW: s = "bow"; break; s = "sword";
break;
case AXE:
s = "axe";
break;
case WARHAMMER:
s = "warhammer";
break;
case BOW:
s = "bow";
break;
} }
return s; return s;
} }

View File

@ -10,12 +10,13 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
OrcKing king = new OrcKing(); OrcKing king = new OrcKing();
king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle"));
king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); king.makeRequest(new Request(RequestType.TORTURE_PRISONER,
king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); "torture prisoner"));
king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax"));
} }
} }

View File

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

View File

@ -8,18 +8,18 @@ package com.iluwatar;
*/ */
public class App { public class App {
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();
goblin.printStatus(); goblin.printStatus();
wizard.castSpell(new ShrinkSpell(), goblin); wizard.castSpell(new ShrinkSpell(), goblin);
goblin.printStatus(); goblin.printStatus();
wizard.castSpell(new InvisibilitySpell(), goblin); wizard.castSpell(new InvisibilitySpell(), goblin);
goblin.printStatus(); goblin.printStatus();
wizard.undoLastSpell(); wizard.undoLastSpell();
goblin.printStatus(); goblin.printStatus();
} }
} }

View File

@ -2,9 +2,7 @@ package com.iluwatar;
public enum Size { public enum Size {
SMALL, SMALL, NORMAL, LARGE;
NORMAL,
LARGE;
@Override @Override
public String toString() { public String toString() {
@ -27,5 +25,4 @@ public enum Size {
return s; return s;
} }
} }

View File

@ -26,6 +26,7 @@ public abstract class Target {
public abstract String toString(); public abstract String toString();
public void printStatus() { 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,8 +2,7 @@ package com.iluwatar;
public enum Visibility { public enum Visibility {
VISIBLE, VISIBLE, INVISIBLE;
INVISIBLE;
@Override @Override
public String toString() { public String toString() {

View File

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

View File

@ -26,7 +26,7 @@ public abstract class LetterComposite {
public void print() { public void print() {
printThisBefore(); printThisBefore();
for (LetterComposite letter: children) { for (LetterComposite letter : children) {
letter.print(); letter.print();
} }
printThisAfter(); printThisAfter();

View File

@ -10,15 +10,20 @@ public class Messenger {
List<Word> words = new ArrayList<Word>(); 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('W'), 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('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('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'), new Letter('i'), new Letter('p')))); words.add(new Word(Arrays.asList(new Letter('w'), 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('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('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('a'), new Letter('y')))); words.add(new Word(Arrays.asList(new Letter('w'), new Letter('a'),
new Letter('y'))));
return new Sentence(words); return new Sentence(words);
@ -28,12 +33,18 @@ public class Messenger {
List<Word> words = new ArrayList<Word>(); 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('M'), new Letter('u'),
words.add(new Word(Arrays.asList(new Letter('w'), new Letter('i'), new Letter('n'), new Letter('d')))); new Letter('c'), new Letter('h'))));
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('w'), new Letter('i'),
words.add(new Word(Arrays.asList(new Letter('f'), new Letter('r'), new Letter('o'), new Letter('m')))); new Letter('n'), new Letter('d'))));
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('p'), new Letter('o'),
words.add(new Word(Arrays.asList(new Letter('m'), new Letter('o'), new Letter('u'), new Letter('t'), new Letter('h')))); 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); return new Sentence(words);

View File

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

View File

@ -5,7 +5,7 @@ import java.util.List;
public class Word extends LetterComposite { public class Word extends LetterComposite {
public Word(List<Letter> letters) { public Word(List<Letter> letters) {
for (Letter l: letters) { for (Letter l : letters) {
this.add(l); this.add(l);
} }
} }

View File

@ -9,16 +9,16 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("A simple looking troll approaches."); System.out.println("A simple looking troll approaches.");
Hostile troll = new Troll(); Hostile troll = new Troll();
troll.attack(); troll.attack();
troll.fleeBattle(); troll.fleeBattle();
System.out.println("\nA smart looking troll surprises you."); System.out.println("\nA smart looking troll surprises you.");
Hostile smart = new SmartTroll(new Troll()); Hostile smart = new SmartTroll(new Troll());
smart.attack(); smart.attack();
smart.fleeBattle(); smart.fleeBattle();
} }
} }

View File

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

View File

@ -12,16 +12,17 @@ import java.util.concurrent.Executors;
*/ */
public class App { public class App {
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);
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
executorService.execute(new Runnable() { executorService.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
while (inventory.addItem(new Item())); while (inventory.addItem(new Item()))
} ;
}); }
} });
} }
}
} }

View File

@ -5,7 +5,6 @@ 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;
public class Inventory { public class Inventory {
private int inventorySize; private int inventorySize;
@ -17,16 +16,16 @@ public class Inventory {
this.items = new ArrayList<Item>(inventorySize); this.items = new ArrayList<Item>(inventorySize);
} }
public boolean addItem(Item item){ public boolean addItem(Item item) {
if(items.size()<inventorySize){ if (items.size() < inventorySize) {
lock.lock(); lock.lock();
try{ try {
if(items.size()<inventorySize){ if (items.size() < inventorySize) {
items.add(item); items.add(item);
System.out.println(Thread.currentThread()); System.out.println(Thread.currentThread());
return true; return true;
} }
}finally{ } finally {
lock.unlock(); lock.unlock();
} }
} }

View File

@ -7,10 +7,10 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade(); DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade();
facade.startNewDay(); facade.startNewDay();
facade.digOutGold(); facade.digOutGold();
facade.endDay(); facade.endDay();
} }
} }

View File

@ -15,20 +15,20 @@ public class DwarvenGoldmineFacade {
} }
public void startNewDay() { public void startNewDay() {
for (DwarvenMineWorker worker: workers) { for (DwarvenMineWorker worker : workers) {
worker.wakeUp(); worker.wakeUp();
worker.goToMine(); worker.goToMine();
} }
} }
public void digOutGold() { public void digOutGold() {
for (DwarvenMineWorker worker: workers) { for (DwarvenMineWorker worker : workers) {
worker.work(); worker.work();
} }
} }
public void endDay() { public void endDay() {
for (DwarvenMineWorker worker: workers) { for (DwarvenMineWorker worker : workers) {
worker.goHome(); worker.goHome();
worker.goToSleep(); worker.goToSleep();
} }

View File

@ -9,20 +9,20 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
Blacksmith blacksmith; Blacksmith blacksmith;
Weapon weapon; Weapon weapon;
blacksmith = new OrcBlacksmith(); blacksmith = new OrcBlacksmith();
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
System.out.println(weapon); System.out.println(weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.AXE); weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
System.out.println(weapon); System.out.println(weapon);
blacksmith = new ElfBlacksmith(); blacksmith = new ElfBlacksmith();
weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD); weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
System.out.println(weapon); System.out.println(weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
System.out.println(weapon); System.out.println(weapon);
} }
} }

View File

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

View File

@ -43,13 +43,13 @@ public class AlchemistShop {
System.out.println("Enumerating top shelf potions\n"); System.out.println("Enumerating top shelf potions\n");
for (Potion p: topShelf) { for (Potion p : topShelf) {
p.drink(); p.drink();
} }
System.out.println("\nEnumerating bottom shelf potions\n"); System.out.println("\nEnumerating bottom shelf potions\n");
for (Potion p: bottomShelf) { for (Potion p : bottomShelf) {
p.drink(); p.drink();
} }

View File

@ -9,8 +9,8 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
AlchemistShop alchemistShop = new AlchemistShop(); AlchemistShop alchemistShop = new AlchemistShop();
alchemistShop.enumerate(); alchemistShop.enumerate();
} }
} }

View File

@ -4,7 +4,8 @@ public class HealingPotion implements Potion {
@Override @Override
public void drink() { 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 @Override
public void drink() { 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 @Override
public void drink() { 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 @Override
public void drink() { 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

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

View File

@ -4,7 +4,8 @@ public class StrengthPotion implements Potion {
@Override @Override
public void drink() { 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

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

View File

@ -5,7 +5,8 @@ public class MultiplyExpression extends Expression {
private Expression leftExpression; private Expression leftExpression;
private Expression rightExpression; private Expression rightExpression;
public MultiplyExpression(Expression leftExpression, Expression rightExpression) { public MultiplyExpression(Expression leftExpression,
Expression rightExpression) {
this.leftExpression = leftExpression; this.leftExpression = leftExpression;
this.rightExpression = rightExpression; this.rightExpression = rightExpression;
} }

View File

@ -9,33 +9,33 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
TreasureChest chest = new TreasureChest(); TreasureChest chest = new TreasureChest();
ItemIterator ringIterator = chest.Iterator(ItemType.RING); ItemIterator ringIterator = chest.Iterator(ItemType.RING);
while (ringIterator.hasNext()) { while (ringIterator.hasNext()) {
System.out.println(ringIterator.next()); System.out.println(ringIterator.next());
} }
System.out.println("----------"); System.out.println("----------");
ItemIterator potionIterator = chest.Iterator(ItemType.POTION); ItemIterator potionIterator = chest.Iterator(ItemType.POTION);
while (potionIterator.hasNext()) { while (potionIterator.hasNext()) {
System.out.println(potionIterator.next()); System.out.println(potionIterator.next());
} }
System.out.println("----------"); System.out.println("----------");
ItemIterator weaponIterator = chest.Iterator(ItemType.WEAPON); ItemIterator weaponIterator = chest.Iterator(ItemType.WEAPON);
while (weaponIterator.hasNext()) { while (weaponIterator.hasNext()) {
System.out.println(weaponIterator.next()); System.out.println(weaponIterator.next());
} }
System.out.println("----------"); System.out.println("----------");
ItemIterator it = chest.Iterator(ItemType.ANY); ItemIterator it = chest.Iterator(ItemType.ANY);
while (it.hasNext()) { while (it.hasNext()) {
System.out.println(it.next()); System.out.println(it.next());
} }
} }
} }

View File

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

View File

@ -39,7 +39,8 @@ public class TreasureChestItemIterator implements ItemIterator {
tempIdx = -1; tempIdx = -1;
break; break;
} }
if (type.equals(ItemType.ANY) || items.get(tempIdx).getType().equals(type)) { if (type.equals(ItemType.ANY)
|| items.get(tempIdx).getType().equals(type)) {
break; break;
} }
} }

View File

@ -8,21 +8,21 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
Party party = new PartyImpl(); Party party = new PartyImpl();
Hobbit hobbit = new Hobbit(); Hobbit hobbit = new Hobbit();
Wizard wizard = new Wizard(); Wizard wizard = new Wizard();
Rogue rogue = new Rogue(); Rogue rogue = new Rogue();
Hunter hunter = new Hunter(); Hunter hunter = new Hunter();
party.addMember(hobbit); party.addMember(hobbit);
party.addMember(wizard); party.addMember(wizard);
party.addMember(rogue); party.addMember(rogue);
party.addMember(hunter); party.addMember(hunter);
hobbit.act(Action.ENEMY); hobbit.act(Action.ENEMY);
wizard.act(Action.TALE); wizard.act(Action.TALE);
rogue.act(Action.GOLD); rogue.act(Action.GOLD);
hunter.act(Action.HUNT); hunter.act(Action.HUNT);
} }
} }

View File

@ -13,7 +13,7 @@ public class PartyImpl implements Party {
@Override @Override
public void act(PartyMember actor, Action action) { public void act(PartyMember actor, Action action) {
for (PartyMember member: members) { for (PartyMember member : members) {
if (member != actor) { if (member != actor) {
member.partyAction(action); member.partyAction(action);
} }

View File

@ -11,26 +11,26 @@ import java.util.Stack;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
Stack<StarMemento> states = new Stack<>(); Stack<StarMemento> states = new Stack<>();
Star star = new Star(StarType.SUN, 10000000, 500000); Star star = new Star(StarType.SUN, 10000000, 500000);
System.out.println(star); System.out.println(star);
states.add(star.getMemento()); states.add(star.getMemento());
star.timePasses(); star.timePasses();
System.out.println(star); System.out.println(star);
states.add(star.getMemento()); states.add(star.getMemento());
star.timePasses(); star.timePasses();
System.out.println(star); System.out.println(star);
states.add(star.getMemento()); states.add(star.getMemento());
star.timePasses(); star.timePasses();
System.out.println(star); System.out.println(star);
states.add(star.getMemento()); states.add(star.getMemento());
star.timePasses(); star.timePasses();
System.out.println(star); System.out.println(star);
while (states.size() > 0) { while (states.size() > 0) {
star.setMemento(states.pop()); star.setMemento(states.pop());
System.out.println(star); System.out.println(star);
} }
} }
} }

View File

@ -63,6 +63,7 @@ public class Star {
@Override @Override
public String toString() { 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

@ -14,18 +14,23 @@ public class StarMementoInternal implements StarMemento {
public StarType getType() { public StarType getType() {
return type; return type;
} }
public void setType(StarType type) { public void setType(StarType type) {
this.type = type; this.type = type;
} }
public int getAgeYears() { public int getAgeYears() {
return ageYears; return ageYears;
} }
public void setAgeYears(int ageYears) { public void setAgeYears(int ageYears) {
this.ageYears = ageYears; this.ageYears = ageYears;
} }
public int getMassTons() { public int getMassTons() {
return massTons; return massTons;
} }
public void setMassTons(int massTons) { public void setMassTons(int massTons) {
this.massTons = massTons; this.massTons = massTons;
} }

View File

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

View File

@ -5,8 +5,8 @@ import java.io.File;
import java.io.FileReader; import java.io.FileReader;
/** /**
* Every instance of this class represents the Model component * Every instance of this class represents the Model component in the
* in the Model-View-Presenter architectural pattern. * Model-View-Presenter architectural pattern.
* *
* It is responsible for reading and loading the contents of a given file. * It is responsible for reading and loading the contents of a given file.
*/ */
@ -27,11 +27,12 @@ public class FileLoader {
*/ */
public String loadData() { public String loadData() {
try { try {
BufferedReader br = new BufferedReader(new FileReader(new File(this.fileName))); BufferedReader br = new BufferedReader(new FileReader(new File(
this.fileName)));
String text = ""; String text = "";
String line = ""; String line = "";
while( (line = br.readLine()) != null ) { while ((line = br.readLine()) != null) {
text += line + "\n"; text += line + "\n";
} }
@ -41,7 +42,7 @@ public class FileLoader {
return text; return text;
} }
catch(Exception e) { catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -51,7 +52,8 @@ public class FileLoader {
/** /**
* Sets the path of the file to be loaded, to the given value. * Sets the path of the file to be loaded, to the given value.
* *
* @param fileName The path of the file to be loaded. * @param fileName
* The path of the file to be loaded.
*/ */
public void setFileName(String fileName) { public void setFileName(String fileName) {
this.fileName = fileName; this.fileName = fileName;

View File

@ -14,10 +14,11 @@ import javax.swing.JTextArea;
import javax.swing.JTextField; import javax.swing.JTextField;
/** /**
* This class is the GUI implementation of the View component * This class is the GUI implementation of the View component In the
* In the Model-View-Presenter pattern. * Model-View-Presenter pattern.
*/ */
public class FileSelectorJFrame extends JFrame implements FileSelectorView, ActionListener { public class FileSelectorJFrame extends JFrame implements FileSelectorView,
ActionListener {
/** /**
* Default serial version ID. * Default serial version ID.
@ -45,8 +46,7 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
private JLabel contents; private JLabel contents;
/** /**
* The text field for giving the name of the file * The text field for giving the name of the file that we want to open.
* that we want to open.
*/ */
private JTextField input; private JTextField input;
@ -142,13 +142,13 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if(e.getSource() == this.OK) { if (e.getSource() == this.OK) {
this.fileName = this.input.getText(); this.fileName = this.input.getText();
presenter.fileNameChanged(); presenter.fileNameChanged();
presenter.confirmed(); presenter.confirmed();
} }
else if(e.getSource() == this.cancel) { else if (e.getSource() == this.cancel) {
presenter.cancelled(); presenter.cancelled();
} }
} }

View File

@ -1,10 +1,11 @@
package com.iluwatar; package com.iluwatar;
/** /**
* Every instance of this class represents the Presenter component * Every instance of this class represents the Presenter component in the
* in the Model-View-Presenter architectural pattern. * Model-View-Presenter architectural pattern.
* *
* It is responsible for reacting to the user's actions and update the View component. * It is responsible for reacting to the user's actions and update the View
* component.
*/ */
public class FileSelectorPresenter { public class FileSelectorPresenter {
@ -21,7 +22,8 @@ public class FileSelectorPresenter {
/** /**
* Constructor * Constructor
* *
* @param view The view component that the presenter will interact with. * @param view
* The view component that the presenter will interact with.
*/ */
public FileSelectorPresenter(FileSelectorView view) { public FileSelectorPresenter(FileSelectorView view) {
this.view = view; this.view = view;
@ -30,7 +32,8 @@ public class FileSelectorPresenter {
/** /**
* Sets the FileLoader object, to the value given as parameter. * Sets the FileLoader object, to the value given as parameter.
* *
* @param loader The new FileLoader object(the Model component). * @param loader
* The new FileLoader object(the Model component).
*/ */
public void setLoader(FileLoader loader) { public void setLoader(FileLoader loader) {
this.loader = loader; this.loader = loader;
@ -52,12 +55,12 @@ public class FileSelectorPresenter {
} }
public void confirmed() { public void confirmed() {
if(loader.getFileName() == null || loader.getFileName().equals("")) { if (loader.getFileName() == null || loader.getFileName().equals("")) {
view.showMessage("Please give the name of the file first!"); view.showMessage("Please give the name of the file first!");
return; return;
} }
if(loader.fileExists()) { if (loader.fileExists()) {
String data = loader.loadData(); String data = loader.loadData();
view.displayData(data); view.displayData(data);
} }

View File

@ -1,14 +1,14 @@
package com.iluwatar; package com.iluwatar;
/** /**
* Every instance of this class represents the Stub component in * Every instance of this class represents the Stub component in the
* the Model-View-Presenter architectural pattern. * Model-View-Presenter architectural pattern.
* *
* The stub implements the View interface and it is useful when * The stub implements the View interface and it is useful when we want the test
* we want the test the reaction to user events, such as mouse clicks. * the reaction to user events, such as mouse clicks.
* *
* Since we can not test the GUI directly, the MVP pattern provides * Since we can not test the GUI directly, the MVP pattern provides this
* this functionality through the View's dummy implementation, the Stub. * functionality through the View's dummy implementation, the Stub.
*/ */
public class FileSelectorStub implements FileSelectorView { public class FileSelectorStub implements FileSelectorView {

View File

@ -1,9 +1,8 @@
package com.iluwatar; package com.iluwatar;
/** /**
* This interface represents the View component in the * This interface represents the View component in the Model-View-Presenter
* Model-View-Presenter pattern. It can be implemented * pattern. It can be implemented by either the GUI components, or by the Stub.
* by either the GUI components, or by the Stub.
*/ */
public interface FileSelectorView { public interface FileSelectorView {
@ -25,7 +24,8 @@ public interface FileSelectorView {
/** /**
* Sets the presenter component, to the one given as parameter. * Sets the presenter component, to the one given as parameter.
* *
* @param presenter The new presenter component. * @param presenter
* The new presenter component.
*/ */
public void setPresenter(FileSelectorPresenter presenter); public void setPresenter(FileSelectorPresenter presenter);
@ -37,7 +37,8 @@ public interface FileSelectorView {
/** /**
* Sets the file's name, to the value given as parameter. * Sets the file's name, to the value given as parameter.
* *
* @param name The new name of the file. * @param name
* The new name of the file.
*/ */
public void setFileName(String name); public void setFileName(String name);
@ -49,14 +50,16 @@ public interface FileSelectorView {
/** /**
* Displays a message to the users. * Displays a message to the users.
* *
* @param message The message to be displayed. * @param message
* The message to be displayed.
*/ */
public void showMessage(String message); public void showMessage(String message);
/** /**
* Displays the data to the view. * Displays the data to the view.
* *
* @param data The data to be written. * @param data
* The data to be written.
*/ */
public void displayData(String data); public void displayData(String data);
} }

View File

@ -6,8 +6,8 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
/** /**
* This test case is responsible for testing our application * This test case is responsible for testing our application by taking advantage
* by taking advantage of the Model-View-Controller architectural pattern. * of the Model-View-Controller architectural pattern.
*/ */
public class FileSelectorPresenterTest { public class FileSelectorPresenterTest {
@ -26,7 +26,6 @@ public class FileSelectorPresenterTest {
*/ */
private FileLoader loader; private FileLoader loader;
/** /**
* Initializes the components of the test case. * Initializes the components of the test case.
*/ */
@ -64,8 +63,8 @@ public class FileSelectorPresenterTest {
} }
/** /**
* Tests if we receive a confirmation when we attempt to open a file * Tests if we receive a confirmation when we attempt to open a file that
* that it's name is null or an empty string. * it's name is null or an empty string.
*/ */
@Test @Test
public void fileConfirmationWhenNameIsNull() { public void fileConfirmationWhenNameIsNull() {
@ -80,8 +79,8 @@ public class FileSelectorPresenterTest {
} }
/** /**
* Tests if we receive a confirmation when we attempt to open a file * Tests if we receive a confirmation when we attempt to open a file that it
* that it doesn't exist. * doesn't exist.
*/ */
@Test @Test
public void fileConfirmationWhenFileDoesNotExist() { public void fileConfirmationWhenFileDoesNotExist() {

View File

@ -8,16 +8,16 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
Weather weather = new Weather(); Weather weather = new Weather();
weather.addObserver(new Orcs()); weather.addObserver(new Orcs());
weather.addObserver(new Hobbits()); weather.addObserver(new Hobbits());
weather.timePasses(); weather.timePasses();
weather.timePasses(); weather.timePasses();
weather.timePasses(); weather.timePasses();
weather.timePasses(); weather.timePasses();
} }
} }

View File

@ -6,7 +6,8 @@ public class Hobbits implements WeatherObserver {
public void update(WeatherType currentWeather) { public void update(WeatherType currentWeather) {
switch (currentWeather) { switch (currentWeather) {
case COLD: case COLD:
System.out.println("The hobbits are shivering in the cold weather."); System.out
.println("The hobbits are shivering in the cold weather.");
break; break;
case RAINY: case RAINY:
System.out.println("The hobbits look for cover from the rain."); System.out.println("The hobbits look for cover from the rain.");
@ -15,7 +16,8 @@ public class Hobbits implements WeatherObserver {
System.out.println("The happy hobbits bade in the warm sun."); System.out.println("The happy hobbits bade in the warm sun.");
break; break;
case WINDY: case WINDY:
System.out.println("The hobbits hold their hats tightly in the windy weather."); System.out
.println("The hobbits hold their hats tightly in the windy weather.");
break; break;
default: default:
break; break;

View File

@ -5,8 +5,8 @@ import java.util.List;
/** /**
* *
* Weather can be observed by implementing WeatherObserver * Weather can be observed by implementing WeatherObserver interface and
* interface and registering as listener. * registering as listener.
* *
*/ */
public class Weather { public class Weather {
@ -49,7 +49,7 @@ public class Weather {
} }
private void notifyObservers() { private void notifyObservers() {
for (WeatherObserver obs: observers) { for (WeatherObserver obs : observers) {
obs.update(currentWeather); obs.update(currentWeather);
} }
} }

View File

@ -2,10 +2,7 @@ package com.iluwatar;
public enum WeatherType { public enum WeatherType {
SUNNY, SUNNY, RAINY, WINDY, COLD;
RAINY,
WINDY,
COLD;
public String toString() { public String toString() {
return this.name().toLowerCase(); return this.name().toLowerCase();

View File

@ -9,26 +9,28 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
HeroFactory factory; HeroFactory factory;
Mage mage; Mage mage;
Warlord warlord; Warlord warlord;
Beast beast; Beast beast;
factory = new HeroFactoryImpl(new ElfMage(), new ElfWarlord(), new ElfBeast()); factory = new HeroFactoryImpl(new ElfMage(), new ElfWarlord(),
mage = factory.createMage(); new ElfBeast());
warlord = factory.createWarlord(); mage = factory.createMage();
beast = factory.createBeast(); warlord = factory.createWarlord();
System.out.println(mage); beast = factory.createBeast();
System.out.println(warlord); System.out.println(mage);
System.out.println(beast); System.out.println(warlord);
System.out.println(beast);
factory = new HeroFactoryImpl(new OrcMage(), new OrcWarlord(), new OrcBeast()); factory = new HeroFactoryImpl(new OrcMage(), new OrcWarlord(),
mage = factory.createMage(); new OrcBeast());
warlord = factory.createWarlord(); mage = factory.createMage();
beast = factory.createBeast(); warlord = factory.createWarlord();
System.out.println(mage); beast = factory.createBeast();
System.out.println(warlord); System.out.println(mage);
System.out.println(beast); System.out.println(warlord);
} System.out.println(beast);
}
} }

View File

@ -7,14 +7,14 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
WizardTowerProxy tower = new WizardTowerProxy(); WizardTowerProxy tower = new WizardTowerProxy();
tower.enter(new Wizard("Red wizard")); tower.enter(new Wizard("Red wizard"));
tower.enter(new Wizard("White wizard")); tower.enter(new Wizard("White wizard"));
tower.enter(new Wizard("Black wizard")); tower.enter(new Wizard("Black wizard"));
tower.enter(new Wizard("Green wizard")); tower.enter(new Wizard("Green wizard"));
tower.enter(new Wizard("Brown wizard")); tower.enter(new Wizard("Brown wizard"));
} }
} }

View File

@ -8,12 +8,12 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
IvoryTower ivoryTower1 = IvoryTower.getInstance(); IvoryTower ivoryTower1 = IvoryTower.getInstance();
IvoryTower ivoryTower2 = IvoryTower.getInstance(); IvoryTower ivoryTower2 = IvoryTower.getInstance();
System.out.println("ivoryTower1=" + ivoryTower1); System.out.println("ivoryTower1=" + ivoryTower1);
System.out.println("ivoryTower2=" + ivoryTower2); System.out.println("ivoryTower2=" + ivoryTower2);
} }
} }

View File

@ -9,7 +9,8 @@ public class IvoryTower {
private static IvoryTower instance = new IvoryTower(); private static IvoryTower instance = new IvoryTower();
private IvoryTower() {} private IvoryTower() {
}
public static IvoryTower getInstance() { public static IvoryTower getInstance() {
return instance; return instance;

View File

@ -9,14 +9,14 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
Mammoth mammoth = new Mammoth(); Mammoth mammoth = new Mammoth();
mammoth.observe(); mammoth.observe();
mammoth.timePasses(); mammoth.timePasses();
mammoth.observe(); mammoth.observe();
mammoth.timePasses(); mammoth.timePasses();
mammoth.observe(); mammoth.observe();
} }
} }

View File

@ -8,15 +8,15 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("Green dragon spotted ahead!"); System.out.println("Green dragon spotted ahead!");
DragonSlayer dragonSlayer = new DragonSlayer(new MeleeStrategy()); DragonSlayer dragonSlayer = new DragonSlayer(new MeleeStrategy());
dragonSlayer.goToBattle(); dragonSlayer.goToBattle();
System.out.println("Red dragon emerges."); System.out.println("Red dragon emerges.");
dragonSlayer.changeStrategy(new ProjectileStrategy()); dragonSlayer.changeStrategy(new ProjectileStrategy());
dragonSlayer.goToBattle(); dragonSlayer.goToBattle();
System.out.println("Black dragon lands before you."); System.out.println("Black dragon lands before you.");
dragonSlayer.changeStrategy(new SpellStrategy()); dragonSlayer.changeStrategy(new SpellStrategy());
dragonSlayer.goToBattle(); dragonSlayer.goToBattle();
} }
} }

View File

@ -4,7 +4,8 @@ public class ProjectileStrategy implements DragonSlayingStrategy {
@Override @Override
public void execute() { public void execute() {
System.out.println("You shoot the dragon with the magical crossbow and it falls dead on the ground!"); System.out
.println("You shoot the dragon with the magical crossbow and it falls dead on the ground!");
} }
} }

View File

@ -4,7 +4,8 @@ public class SpellStrategy implements DragonSlayingStrategy {
@Override @Override
public void execute() { public void execute() {
System.out.println("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"); System.out
.println("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!");
} }
} }

View File

@ -8,10 +8,10 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
HalflingThief thief = new HalflingThief(new HitAndRunMethod()); HalflingThief thief = new HalflingThief(new HitAndRunMethod());
thief.steal(); thief.steal();
thief.changeMethod(new SubtleMethod()); thief.changeMethod(new SubtleMethod());
thief.steal(); thief.steal();
} }
} }

View File

@ -9,12 +9,14 @@ public class SubtleMethod extends StealingMethod {
@Override @Override
protected void confuseTarget(String target) { protected void confuseTarget(String target) {
System.out.println("Approach the " + target + " with tears running and hug him!"); System.out.println("Approach the " + target
+ " with tears running and hug him!");
} }
@Override @Override
protected void stealTheItem(String target) { protected void stealTheItem(String target) {
System.out.println("While in close contact grab the " + target + "'s wallet."); System.out.println("While in close contact grab the " + target
+ "'s wallet.");
} }
} }

View File

@ -9,14 +9,14 @@ package com.iluwatar;
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
Commander commander = new Commander( Commander commander = new Commander(new Sergeant(new Soldier(),
new Sergeant(new Soldier(), new Soldier(), new Soldier()), new Soldier(), new Soldier()), new Sergeant(new Soldier(),
new Sergeant(new Soldier(), new Soldier(), new Soldier())); new Soldier(), new Soldier()));
commander.accept(new SoldierVisitor()); commander.accept(new SoldierVisitor());
commander.accept(new SergeantVisitor()); commander.accept(new SergeantVisitor());
commander.accept(new CommanderVisitor()); commander.accept(new CommanderVisitor());
} }
} }

View File

@ -2,7 +2,7 @@ package com.iluwatar;
public class Commander extends Unit { public class Commander extends Unit {
public Commander(Unit ... children) { public Commander(Unit... children) {
super(children); super(children);
} }

View File

@ -2,7 +2,7 @@ package com.iluwatar;
public class Sergeant extends Unit { public class Sergeant extends Unit {
public Sergeant(Unit ... children) { public Sergeant(Unit... children) {
super(children); super(children);
} }

View File

@ -2,7 +2,7 @@ package com.iluwatar;
public class Soldier extends Unit { public class Soldier extends Unit {
public Soldier(Unit ... children) { public Soldier(Unit... children) {
super(children); super(children);
} }

View File

@ -9,12 +9,12 @@ public abstract class Unit {
private Unit[] children; private Unit[] children;
public Unit(Unit ... children) { public Unit(Unit... children) {
this.children = children; this.children = children;
} }
public void accept(UnitVisitor visitor) { public void accept(UnitVisitor visitor) {
for (Unit child: children) { for (Unit child : children) {
child.accept(visitor); child.accept(visitor);
} }
} }

View File

@ -8,7 +8,9 @@ package com.iluwatar;
public interface UnitVisitor { public interface UnitVisitor {
void visitSoldier(Soldier soldier); void visitSoldier(Soldier soldier);
void visitSergeant(Sergeant sergeant); void visitSergeant(Sergeant sergeant);
void visitCommander(Commander commander); void visitCommander(Commander commander);
} }