전략 패턴(Strategy Pattern)

이창호·2022년 3월 21일
0

디자인패턴

목록 보기
2/4

전략 패턴은

행위 디자인 패턴 중 하나로 특정 컨텍스트에서 알고리즘을 별도로 분리하는 설계 방법을 의미합니다. 하나의 기능을 수행하는데, 다양한 알고리즘이 적용될 필요가 있을때 사용됩니다.

이럴때 사용합니다

예를 들어 네비게이션 앱을 사용한다 했을 때, 목적지까지 향하는 길을 안내하기 위해선 도보, 버스, 기차, 차, 자전거에 따라 다른 경로로 안내를 해야 합니다.

그럴때, 전략 패턴를 활용하여 만든다면 쉽게 해결 할 수 있습니다.

코드로 봅시다

public interface MoveStrategy {
    String  move();
}

이동 수단 객체가 상속받을 인터페이스입니다. 지금은 move뿐이지만 다른 기능도 추가할 수 있습니다.

public class Train implements MoveStrategy {
    @Override
    public String move() {
        return "기차로 이동";
    }
}

public class Pedestrian implements MoveStrategy {
    @Override
    public String move() {
        return "도보로 이동";
    }
}

public class Car implements MoveStrategy {
    @Override
    public String move() {
        return "자동차로 이동";
    }
}

public class Bus implements MoveStrategy {
    @Override
    public String move() {
        return "버스로 이동";
    }
}

public class Bicycle implements MoveStrategy {
    @Override
    public String move() {
        return "자전거로 이동";
    }
}

각 이동수단 객체들이 인터페이스를 상속받아 move 메서드를 구현하였습니다.

public class Action {
    private MoveStrategy moveStrategy;
    private final String transportation;

    public Action(String transportation) {
        this.transportation = transportation;
    }

    public void setMoveStrategy() {
        switch (transportation) {
            case "bus" -> this.moveStrategy = new Bus();
            case "car" -> this.moveStrategy = new Car();
            case "bicycle" -> this.moveStrategy = new Bicycle();
            case "train" -> this.moveStrategy = new Train();
        }
    }

    public String go() {
        setMoveStrategy();
        return moveStrategy.move();
    }
}
public class Client {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String transportation = "";

        System.out.println("이동 수단을 입력해 주세요.");

        transportation = sc.next();

        Action action = new Action(transportation);

        System.out.println(action.go());
    }
}

이제 Action 클래스는 CLient 클래스에서 입력한 이동수단을 찾은 뒤 go란 메서드를 실행시킵니다.

정리

위 코드는 컨텍스트(Action 클래스)에서 전략(MoveStrategy 인터페이스를 구현 한 클래스)를 찾은 뒤 클라이언트(Client 클래스)가 요청한 기능을 수행합니다.

전략 패턴은 특정 목적을 이루기 위해 어떤 일을 수행해야 하는 방식이나 규칙을 정하는 알고리즘이라 생각합니다.

아래 참고글을 보신다면 좀 더 도움이 될겁니다! 그럼 궁금한 점이나 부족한 점은 댓글로 알려주세요~

참고

https://refactoring.guru/design-patterns/strategy
https://velog.io/@kyle/디자인-패턴-전략패턴이란
https://victorydntmd.tistory.com/292
https://velog.io/@y_dragonrise/디자인-패턴-전략-패턴Strategy-Pattern

profile
이타적인 기회주의자

0개의 댓글