개발기초/Design Pattern

1. Strategy Pattern

이상한개발자 2020. 2. 24. 12:54

0. Strategy pattern?

  • 행위를 클래스로 캡슐화해 동적으로 행위를 자유롭게 바꿀 수 있게 해주는 패턴
  • 스트래티지를 활용하면 알고리즘을 사용하는 클라이언트와는 독립적으로 알고리즘을 변경할 수 있습니다.

1. Strategy pattern을 구성하는 3대 요소

  1) 전략 메서드를 가진 전략 객체

  2) 전략 객체를 사용하는 컨텍스트(전략 객체의 사용자/소비자)

  3) 전략 객체를 생성해 컨텍스트에 주입하는 클라이언트(제3자, 전략 객체의 공급자)

 

Starategy Pattern UML(출처: 위키백과)

 

 

2. Strategy Pattern 예제

(출처: https://limkydev.tistory.com/84)

 

Strategy.java (전략 인터페이스 정의)

public interface Strategy {
    void runStrategy();
}

StarategyGun.java (전략 인터페이스 구현1)

public class StrategyGun implements Strategy{
 
    @Override
    public void runStrategy() {
        // TODO Auto-generated method stub
        System.out.println("탕! 타탕! 탕탕!");
         
    }
 
}

StrategyGrenade.java (전략 인터페이스 구현2)

public class StrategyGrenade implements Strategy{
 
    @Override
    public void runStrategy() {
        // TODO Auto-generated method stub
        System.out.println("수류탄 투척~! 쾅!!!!");
         
    }
 
}

Solider.java(전략을 사용할 Context)

public class Solider {
    void runContext(Strategy strategy) {
        System.out.println("배틀 그라운드 시작");
        strategy.runStrategy();
        System.out.println("배틀 종료");
    }
 
}

Client.java (Client - 전략을 생성하고 컨텍스트에게 주입시키는 역할)

public class Client {
 
    public static void main(String[] args) {
        Strategy strategy = null;
        Solider rambo = new Solider();
        strategy = new StrategyGun();
         
        rambo.runContext(strategy);
         
        System.out.println("\n");
        strategy = new StrategyGrenade();
         
        rambo.runContext(strategy);
    }
 
}

 

3. 요약 및 결론

 1) 전략 인터페이스를 하나 정의하고 (=Strategy 인터페이스를 하나 정의하고)

 2) 그 전략 인터페이스를 구현한 구현체를 여러개로 만들면 (=Strategy 인터페이스를 받아서 총도 만들고 수류탄도 만들면)

 3) Client가 상황에 맞는 전략 구현체를 불러와서 전략을 실행시킬 수 있다. (Client의 선택에 따라 총도 쏠 수 있고, 수류탄도 던질 수 있다.)