added strategy pattern sample
This commit is contained in:
17
strategy/src/main/java/com/iluwatar/App.java
Normal file
17
strategy/src/main/java/com/iluwatar/App.java
Normal 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();
|
||||
}
|
||||
}
|
18
strategy/src/main/java/com/iluwatar/DragonSlayer.java
Normal file
18
strategy/src/main/java/com/iluwatar/DragonSlayer.java
Normal 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();
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.iluwatar;
|
||||
|
||||
public interface DragonSlayingStrategy {
|
||||
|
||||
void execute();
|
||||
|
||||
}
|
10
strategy/src/main/java/com/iluwatar/MeleeStrategy.java
Normal file
10
strategy/src/main/java/com/iluwatar/MeleeStrategy.java
Normal 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!");
|
||||
}
|
||||
|
||||
}
|
10
strategy/src/main/java/com/iluwatar/ProjectileStrategy.java
Normal file
10
strategy/src/main/java/com/iluwatar/ProjectileStrategy.java
Normal 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!");
|
||||
}
|
||||
|
||||
}
|
10
strategy/src/main/java/com/iluwatar/SpellStrategy.java
Normal file
10
strategy/src/main/java/com/iluwatar/SpellStrategy.java
Normal 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!");
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user