|
| 1 | +--- |
| 2 | +layout: pattern |
| 3 | +title: Strategy |
| 4 | +folder: strategy |
| 5 | +permalink: /patterns/strategy/ |
| 6 | +categories: Behavioral |
| 7 | +tags: |
| 8 | + - Gang of Four |
| 9 | +--- |
| 10 | + |
| 11 | +## 동의어 |
| 12 | + |
| 13 | +정책(Policy) 패턴 |
| 14 | + |
| 15 | +## 의도 |
| 16 | + |
| 17 | +알고리즘군을 정의하고 각 알고리즘을 캡슐화하고 상호 변경 가능하게 만듭니다. 전략(Strategy) 패턴을 사용하면 알고리즘이 이를 사용하는 클라이언트와 독립적일 수 있습니다. |
| 18 | + |
| 19 | +## 설명 |
| 20 | + |
| 21 | +실제 예제 |
| 22 | + |
| 23 | +> 드래곤을 사냥하는 것은 위험한 일입니다. 경험이 쌓이면 쉬워집니다. 베테랑 사냥꾼들은 서로 다른 유형의 드래곤에 대해 서로 다른 전투 전략을 개발했습니다. |
| 24 | +
|
| 25 | +평범한 말로는 |
| 26 | + |
| 27 | +> 전략(Strategy) 패턴을 사용하면 런타임에 가장 적합한 알고리즘을 선택할 수 있습니다. |
| 28 | +
|
| 29 | +Wikipedia는 |
| 30 | + |
| 31 | +> 컴퓨터 프로그래밍에서 전략 패턴(정책 패턴이라고도 함)은 런타임에 알고리즘을 선택할 수 있는 행동 소프트웨어 디자인 패턴입니다. |
| 32 | +
|
| 33 | +**프로그래밍 예** |
| 34 | + |
| 35 | +먼저 드래곤 사냥 전략 인터페이스와 그 구현을 살펴봅니다. |
| 36 | + |
| 37 | +```java |
| 38 | +@FunctionalInterface |
| 39 | +public interface DragonSlayingStrategy { |
| 40 | + |
| 41 | + void execute(); |
| 42 | +} |
| 43 | + |
| 44 | +@Slf4j |
| 45 | +public class MeleeStrategy implements DragonSlayingStrategy { |
| 46 | + |
| 47 | + @Override |
| 48 | + public void execute() { |
| 49 | + LOGGER.info("With your Excalibur you sever the dragon's head!"); |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +@Slf4j |
| 54 | +public class ProjectileStrategy implements DragonSlayingStrategy { |
| 55 | + |
| 56 | + @Override |
| 57 | + public void execute() { |
| 58 | + LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!"); |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +@Slf4j |
| 63 | +public class SpellStrategy implements DragonSlayingStrategy { |
| 64 | + |
| 65 | + @Override |
| 66 | + public void execute() { |
| 67 | + LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"); |
| 68 | + } |
| 69 | +} |
| 70 | +``` |
| 71 | + |
| 72 | +그리고 여기 상대하는 드래곤에 따라 자신의 전투 전략을 선택할 수 있는 강력한 드래곤 슬레이어가 있습니다. |
| 73 | + |
| 74 | +```java |
| 75 | +public class DragonSlayer { |
| 76 | + |
| 77 | + private DragonSlayingStrategy strategy; |
| 78 | + |
| 79 | + public DragonSlayer(DragonSlayingStrategy strategy) { |
| 80 | + this.strategy = strategy; |
| 81 | + } |
| 82 | + |
| 83 | + public void changeStrategy(DragonSlayingStrategy strategy) { |
| 84 | + this.strategy = strategy; |
| 85 | + } |
| 86 | + |
| 87 | + public void goToBattle() { |
| 88 | + strategy.execute(); |
| 89 | + } |
| 90 | +} |
| 91 | +``` |
| 92 | + |
| 93 | +마지막으로 여기 드래곤 슬레이어가 행동합니다. |
| 94 | + |
| 95 | +```java |
| 96 | + LOGGER.info("Green dragon spotted ahead!"); |
| 97 | + var dragonSlayer = new DragonSlayer(new MeleeStrategy()); |
| 98 | + dragonSlayer.goToBattle(); |
| 99 | + LOGGER.info("Red dragon emerges."); |
| 100 | + dragonSlayer.changeStrategy(new ProjectileStrategy()); |
| 101 | + dragonSlayer.goToBattle(); |
| 102 | + LOGGER.info("Black dragon lands before you."); |
| 103 | + dragonSlayer.changeStrategy(new SpellStrategy()); |
| 104 | + dragonSlayer.goToBattle(); |
| 105 | +``` |
| 106 | + |
| 107 | +프로그램 출력: |
| 108 | + |
| 109 | +``` |
| 110 | + Green dragon spotted ahead! |
| 111 | + With your Excalibur you sever the dragon's head! |
| 112 | + Red dragon emerges. |
| 113 | + You shoot the dragon with the magical crossbow and it falls dead on the ground! |
| 114 | + Black dragon lands before you. |
| 115 | + You cast the spell of disintegration and the dragon vaporizes in a pile of dust! |
| 116 | +``` |
| 117 | + |
| 118 | +또한 Java 8의 새로운 기능인 Lambda Expressions은 구현을 위한 또 다른 접근 방식을 제공합니다: |
| 119 | + |
| 120 | +```java |
| 121 | +public class LambdaStrategy { |
| 122 | + |
| 123 | + private static final Logger LOGGER = LoggerFactory.getLogger(LambdaStrategy.class); |
| 124 | + |
| 125 | + public enum Strategy implements DragonSlayingStrategy { |
| 126 | + MeleeStrategy(() -> LOGGER.info( |
| 127 | + "With your Excalibur you severe the dragon's head!")), |
| 128 | + ProjectileStrategy(() -> LOGGER.info( |
| 129 | + "You shoot the dragon with the magical crossbow and it falls dead on the ground!")), |
| 130 | + SpellStrategy(() -> LOGGER.info( |
| 131 | + "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); |
| 132 | + |
| 133 | + private final DragonSlayingStrategy dragonSlayingStrategy; |
| 134 | + |
| 135 | + Strategy(DragonSlayingStrategy dragonSlayingStrategy) { |
| 136 | + this.dragonSlayingStrategy = dragonSlayingStrategy; |
| 137 | + } |
| 138 | + |
| 139 | + @Override |
| 140 | + public void execute() { |
| 141 | + dragonSlayingStrategy.execute(); |
| 142 | + } |
| 143 | + } |
| 144 | +} |
| 145 | +``` |
| 146 | + |
| 147 | +그리고 여기 드래곤 슬레이어가 행동합니다. |
| 148 | + |
| 149 | +```java |
| 150 | + LOGGER.info("Green dragon spotted ahead!"); |
| 151 | + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MeleeStrategy); |
| 152 | + dragonSlayer.goToBattle(); |
| 153 | + LOGGER.info("Red dragon emerges."); |
| 154 | + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.ProjectileStrategy); |
| 155 | + dragonSlayer.goToBattle(); |
| 156 | + LOGGER.info("Black dragon lands before you."); |
| 157 | + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SpellStrategy); |
| 158 | + dragonSlayer.goToBattle(); |
| 159 | +``` |
| 160 | + |
| 161 | +프로그램 출력은 위와 동일합니다. |
| 162 | + |
| 163 | +## 클래스 다이어그램 |
| 164 | + |
| 165 | + |
| 166 | + |
| 167 | +## 적용 가능성 |
| 168 | + |
| 169 | +다음과 같은 경우 전략(Strategy) 패턴을 사용합니다. |
| 170 | + |
| 171 | +* 비슷한 클래스들이 동작 만 다른 경우가 많이 있습니다. 전략 패턴은 여러 동작 중 하나를 클래스로 구성하는 방법을 제공합니다. |
| 172 | +* 알고리즘의 다양한 변형이 필요합니다. 예를 들어 다양한 공간 / 시간 절충을 반영하는 알고리즘을 정의할 수 있습니다. 이러한 변형이 알고리즘의 클래스 계층 구조로 구현될 때 전략 패턴을 사용할 수 있습니다. |
| 173 | +* 알고리즘은 클라이언트가 알 필요 없는 데이터를 사용합니다. 전략 패턴을 사용하여 복잡한 알고리즘 별 데이터 구조가 노출되지 않도록 합니다. |
| 174 | +* 클래스는 많은 동작을 정의하며 이러한 동작은 작업에서 여러 조건문으로 나타납니다. 많은 조건부 대신 관련 조건부 분기를 자체 전략 클래스로 이동하세요. |
| 175 | + |
| 176 | +## 튜토리얼 |
| 177 | + |
| 178 | +* [전략 패턴 튜토리얼](https://www.journaldev.com/1754/strategy-design-pattern-in-java-example-tutorial) |
| 179 | + |
| 180 | +## 크레딧 |
| 181 | + |
| 182 | +* [디자인 패턴: 재사용 가능한 객체 지향 소프트웨어의 요소](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) |
| 183 | +* [자바의 함수형 프로그래밍: Java 8 Lambda 표현식의 강력한 기능 활용](https://www.amazon.com/gp/product/1937785467/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1937785467&linkCode=as2&tag=javadesignpat-20&linkId=7e4e2fb7a141631491534255252fd08b) |
| 184 | +* [헤드 퍼스트 디자인 패턴: 두뇌 친화적인 가이드](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) |
| 185 | +* [패턴으로 리팩토링](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) |
0 commit comments