added strategy pattern sample

This commit is contained in:
Ilkka Seppala
2014-08-23 13:18:53 +03:00
parent 2d0905a5e9
commit 6157f22ea4
8 changed files with 96 additions and 0 deletions

View File

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

View File

@ -0,0 +1,18 @@
package com.iluwatar;
public class DragonSlayer {
private DragonSlayingStrategy strategy;
public DragonSlayer(DragonSlayingStrategy strategy) {
this.strategy = strategy;
}
public void changeStrategy(DragonSlayingStrategy strategy) {
this.strategy = strategy;
}
public void goToBattle() {
strategy.execute();
}
}

View File

@ -0,0 +1,7 @@
package com.iluwatar;
public interface DragonSlayingStrategy {
void execute();
}

View File

@ -0,0 +1,10 @@
package com.iluwatar;
public class MeleeStrategy implements DragonSlayingStrategy {
@Override
public void execute() {
System.out.println("With your Excalibur you severe the dragon's head!");
}
}

View File

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

View File

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