이전 포스트의 테스트에서는 Context의 필드에 Strategy를 주입해서 사용했는데, 전략을 유연하게 변경하기 어려운 단점이 있었다.
이번에는 전략을 실행할 때 직접 파라미터로 전달하는 방법을 알아보자.
// 변하지 않는 부분, 생성자를 통해 필드에 주입받는 방식에서 파라미터 받는 것으로 변경
@Slf4j
public class ContextV2 {
public void execute(Strategy strategy){
long startTime = System.currentTimeMillis();
//비지니스 로직 실행
strategy.call();
//비지니스 로직 종료
long endTime = System.currentTimeMillis();
long resultTime = endTime - startTime;
log.info("resultTime={}", resultTime);
}
}
// 테스트
@Slf4j
public class ContextV2Test {
@Test
void strategyV2(){
ContextV2 context = new ContextV2();
context.execute(new StrategyLogic1());
context.execute(new Strategy() {
@Override
public void call() {
log.info("비지니스 로직2 실행");
}
});
context.execute(() -> log.info("비지니스 로직3 실행"));
}
}
// 결과
15:49:22.645 [main] INFO StrategyLogic1 - 비지니스 로직1 실행
15:49:22.648 [main] INFO ContextV2 - resultTime=5
15:49:22.651 [main] INFO ContextV2Test - 비지니스 로직2 실행
15:49:22.651 [main] INFO ContextV2 - resultTime=0
15:49:22.651 [main] INFO ContextV2Test - 비지니스 로직3 실행
15:49:22.651 [main] INFO ContextV2 - resultTime=0
장점은 전략을 유연하게 변경할 수 있다는 점이 있다.
단점또한 역시 실행할 때 마다 전략을 계속 지정해줘야하는 것이 있다.