Decorator pattern: SmartTroll should be SmartHostile #264

This commit is contained in:
Tom.TH.Lin
2016-01-04 23:07:33 +08:00
parent 4c5f9ae44c
commit 30ca1ea1fb
5 changed files with 41 additions and 24 deletions

View File

@ -8,7 +8,7 @@ package com.iluwatar.decorator;
* runtime.
* <p>
* In this example we show how the simple {@link Troll} first attacks and then flees the battle.
* Then we decorate the {@link Troll} with a {@link SmartTroll} and perform the attack again. You
* Then we decorate the {@link Troll} with a {@link SmartHostile} and perform the attack again. You
* can see how the behavior changes after the decoration.
*
*/
@ -30,7 +30,7 @@ public class App {
// change the behavior of the simple troll by adding a decorator
System.out.println("\nA smart looking troll surprises you.");
Hostile smart = new SmartTroll(troll);
Hostile smart = new SmartHostile(troll);
smart.attack();
smart.fleeBattle();
System.out.printf("Smart troll power %d.\n", smart.getAttackPower());

View File

@ -1,34 +1,34 @@
package com.iluwatar.decorator;
/**
* SmartTroll is a decorator for {@link Hostile} objects. The calls to the {@link Hostile} interface
* SmartHostile is a decorator for {@link Hostile} objects. The calls to the {@link Hostile} interface
* are intercepted and decorated. Finally the calls are delegated to the decorated {@link Hostile}
* object.
*
*/
public class SmartTroll implements Hostile {
public class SmartHostile implements Hostile {
private Hostile decorated;
public SmartTroll(Hostile decorated) {
public SmartHostile(Hostile decorated) {
this.decorated = decorated;
}
@Override
public void attack() {
System.out.println("The troll throws a rock at you!");
System.out.println("It throws a rock at you!");
decorated.attack();
}
@Override
public int getAttackPower() {
// decorated troll power + 20 because it is smart
// decorated hostile's power + 20 because it is smart
return decorated.getAttackPower() + 20;
}
@Override
public void fleeBattle() {
System.out.println("The troll calls for help!");
System.out.println("It calls for help!");
decorated.fleeBattle();
}
}

View File

@ -11,7 +11,7 @@ import static org.mockito.internal.verification.VerificationModeFactory.times;
*
* @author Jeroen Meulemeester
*/
public class SmartTrollTest {
public class SmartHostileTest {
@Test
public void testSmartTroll() throws Exception {
@ -19,7 +19,7 @@ public class SmartTrollTest {
final Hostile simpleTroll = spy(new Troll());
// Now we want to decorate the troll to make it smarter ...
final Hostile smartTroll = new SmartTroll(simpleTroll);
final Hostile smartTroll = new SmartHostile(simpleTroll);
assertEquals(30, smartTroll.getAttackPower());
verify(simpleTroll, times(1)).getAttackPower();