티스토리 뷰

Programming/디자인 패턴

Strategy Pattern

Albothyl 2019. 1. 24. 13:21

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();

  }

}

'Programming > 디자인 패턴' 카테고리의 다른 글

Observer Pattern  (0) 2019.01.24
Factory Method Pattern  (0) 2019.01.24
Builder Pattern  (0) 2019.01.24
Template Method Pattern  (0) 2019.01.24
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함