Strategy Pattern

  • Examples:
    • Maps choose shortest path via:
      • car
      • motorbike
      • bus

Implementation

@FunctionalInterface // not needed, but then you can make use of lambdas 
interface DragonSlayingStrategy {
    void execute();
}
 
class MeleeStrategy implements DragonSlayingStrategy {
    @Override
    public void execute() {
        System.out.println("With your Excalibur you sever the dragon's head!");
    }
}
 
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!");
    }
}
 
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!");
    }
}
 
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();
    }
}
  • Driver
public class Test {
    public static void main(String[] args) {
        System.out.println("Green dragon spotted ahead!");
        var 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();
    }
}

UML

Strategy_Pattern_UML