본문 바로가기
스터디/Design Pattern

디자인 패턴 - 전략 패턴 (Strategy Pattern)

by 헤콩 2020. 5. 31.
반응형

전략 패턴 (Strategy Pattern)

 

 

행위 패턴 (Behavioral Pattern) 중 하나

    => 객체나 클래스 사이의 알고리즘이나 책임 분배에 관련된 패턴

    => 1. 한 객체가 혼자 수행할 수 없는 작업을 여러 개의 객체로 어떻게 분배하는지에 대해서 중점을 둔다.

    => 2. 객체 사이의 결합도를 최소화 하는 것에 중점을 둔다.

 

1. 객체들이 할 수 있는 행위 각각에 대해 전략 클래스 생성

2. 유사한 행위들을 캡슐화 하는 인터페이스 정의

3. 객체의 행위를 동적으로 바꾸고 싶은 경우, 직접 행위를 수정하지 않고 전략을 바꿔주므로써 행위를 유연하게 확장하는 방법


인터페이스 (MovableStrategy)

아래 예시에서 운송 수단을 정해주는 전략 클래스들을 캡슐화 하기 위한 인터페이스

public interface MovableStrategy {
    public void move();
}

 

선로이동 클래스 (RailLoadStrategy)

MovableStrategy 인터페이스를 사용하는 전략 클래스 1

public class RailLoadStrategy implements MovableStrategy {
    @Override
    public void move() {
        System.out.println("선로를 통해 이동");
    }
}

 

도로이동 클래스 (LoadStrategy)

MovableStrategy 인터페이스를 사용하는 전략 클래스 2

public class LoadStrategy implements MovableStrategy {
    @Override
    public void move() {
        System.out.println("도로를 통해 이동");
    }
}

 

운송수단 결정 클래스 (Moving)

교통수단에 운송 수단 종류를 결정할 수 있도록 하는 클래스

public class Moving {
    private MovableStrategy ms;

    public void move() {
        ms.move();
    }

    public void setMS(MovableStrategy ms) {
        this.ms = ms;
    }
}

 

교통수단 클래스 (Train, Bus)

public class Train extends Moving {

}
public class Bus extends Moving {

}

 

메인 클래스 (StrategyMain)

public class StrategyMain {

    public static void main(String[] args) {
        Moving train = new Train();
        Moving bus = new Bus();

        train.setMS(new RailLoadStrategy());
        bus.setMS(new LoadStrategy());
        System.out.print("train : ");
        train.move();
        System.out.print("bus : ");
        bus.move();

        System.out.println();

        bus.setMS(new RailLoadStrategy());
        System.out.print("train : ");
        train.move();
        System.out.print("bus : ");
        bus.move();
    }
}

출력 결과

 

 

 

 

 

 

 

 

 

참고 :

 

[디자인패턴] 전략 패턴 ( Strategy Pattern )

전략 패턴 ( Strategy Pattern ) 객체들이 할 수 있는 행위 각각에 대해 전략 클래스를 생성하고, 유사한 행위들을 캡슐화 하는 인터페이스를 정의하여, 객체의 행위를 동적으로 바꾸고 싶은 경우 직��

victorydntmd.tistory.com

 

 

반응형

댓글