[ 전략 패턴 V1 - 예제 ]

Untitled

Context

/**
 * 필드에 전략을 보관하는 방식
 */
@Slf4j
public class ContextV1 {
		
		// Context는 Strategy Interface에만 의존한다. (**다형성**)
		// Strategy의 구현체를 변경하거나 새로 만들어도 Context 코드에는 영향을 주지 않는다.
    private Strategy strategy;

    public ContextV1(Strategy strategy) {
        this.strategy = strategy;
    }

    public void execute(){
        long startTime = System.currentTimeMillis();
        //비즈니스 로직 실행
        strategy.call(); // 위임
        //비즈니스 로직 종료
        long endTime = System.currentTimeMillis();
        long resultTime = endTime - startTime;
        log.info("resultTime={}", resultTime);
    }
}

Strategy

// Strategy Interface (역할)
public interface Strategy {
 void call(); // 변하는 것(핵심 기능 코드)을 구현할 메서드
}

// Strategy Class1 (구현)
@Slf4j
public class StrategyLogic1 implements Strategy{

    @Override
    public void call() {
        log.info("비즈니스 로직1 실행");
    }
}

// Strategy Class2 (구현)
@Slf4j
public class StrategyLogic2 implements Strategy{

    @Override
    public void call() {
        log.info("비즈니스 로직2 실행");
    }
}

Use the strategy pattern

/**
 * 전략 패턴 사용
 * @throws Exception
 */
@Test
public void strategyV1() throws Exception {
    Strategy strategyLogic1 = new StrategyLogic1();
    ContextV1 context1 = new ContextV1(strategyLogic1);
    context1.execute();

    Strategy strategyLogic2 = new StrategyLogic2();
    ContextV1 context2 = new ContextV1(strategyLogic2);
    context2.execute();	
}