Strategy Pattern
Strategy Pattern
- 전략 패턴은 실행 중에 알고리즘을 선택할 수 있게 하는 행위 소프트웨어 디자인 패턴이다.
- 특정한 계열의 알고리즘들을 정의하고 각 알고리즘을 캡슐화하며 이 알고리즘들을 해당 계열 안에서 상호 교체가 가능하게 만든다.
- 전략은 알고리즘을 사용하는 클라이언트와는 독립적으로 다양하게 만든다.
public class MeleeStrategy implements DragonSlayingStrategy {
@Override
public void execute() {
System.out.println("With your Excalibur you sever the dragon's head!");
}
}
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!");
}
}
@FunctionalInterface
public interface DragonSlayingStrategy {
void execute();
}
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();
}
}
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();
}
}