전략 패턴 (Strategy Pattern)
- 템플릿 메서드 패턴은 상속을 통해 문제를 해결했다.
- 전략패턴은
Context라는 곳에 변하지 않는 부분을 두고, 변하는 부분을Strategy라는 인터페이스에서 구현하도록 하여 상속이 아닌위임을 통해 문제를 해결한다.
전략 패턴의 의도
알고리즘 제품군을 정의하고 각각을 캡슐화하여 상호 교환 가능하게 만들자. 전략을 사용하면 알고리즘을 사용하는 클라이언트와 독립적으로 알고리즘을 변경할 수 있다.

Context
@Slf4j
public class Context {
private final Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void execute() {
long startTime = System.currentTimeMillis();
// Logic Start
strategy.call();
// Logic End
long endTime = System.currentTimeMillis();
long result = endTime - startTime;
log.info("result = {}", result);
}
}
Strategy
public interface Strategy {
void call();
}
Test
@Test
void test() {
Strategy strategy1 = new StrategyLogic1();
Context context1 = new Context(strategy1);
Strategy strategy2 = new StrategyLogic1();
Context context2 = new Context(strategy2);
context1.execute();
context2.execute();
}
람다를 사용하여 간소화
@Test
void testLambda() {
Context context1 = new Context(()-> log.info("Strategy 1 start"));
Context context2 = new Context(()-> log.info("Strategy 2 start"));
context1.execute();
context2.execute();
}
21:02:17.234 [Test worker] INFO hello.advanced.trace.mystrategy.StrategyLogic1 - Logic 1 Start
21:02:17.236 [Test worker] INFO hello.advanced.trace.mystrategy.Context - result = 4
21:02:17.238 [Test worker] INFO hello.advanced.trace.mystrategy.StrategyLogic1 - Logic 1 Start
21:02:17.238 [Test worker] INFO hello.advanced.trace.mystrategy.Context - result = 0
참고
'Java > Design Pattern' 카테고리의 다른 글
| Template Method Pattern (0) | 2022.12.02 |
|---|
댓글