이상한 나라의 앨리스에서 재판을 한다.
왕 : “토끼야 모자장수를 들라하라”
토끼 : “모자장수는 들어와라”
토끼 : “모자장수는 증언하라”
모자장수가 증언을 한다.
이후 왕 대신 왕비가 재판을 주관하고, 앨리스의 증언 차례가 온다.
위의 글이 코드라고 가정했을 때 인물이 바뀌면 내용을 수정해야 된다.
이렇게 구체적이면 코드의 유연성이 떨어지기 때문에
왕→ 재판관, 토끼→ 진행자, 모자장수 → 증인
로 변경을 하면(추상화)
기존 코드를 손대지 않아도 된다. (개방-폐쇄 원칙, Open-Closed Principle)즉, 구체적인 것에 의존하지 않고, 추상적인 것에 의존을 해야 된다.(의존 역전 원칙, Dependency Inversion Principle )
전략패턴이란?
전략 패턴(Strategy Pattern)은 알고리즘군을 정의하고
캡슐화
해서 각각의 알고리즘군을 수정해서 쓸 수 있게 해준다.전략 패턴을 사용하면 클라이언트로부터
알고리즘을
분리해서 독립적으로 변경할 수 있다.예제
Doorman 은 처음 쥐를 내보내기로 했다.
그러다 모든 동물의 출입을 금지하기로 하자 도움이 필요하다..!
getOut
의 매개변수가 Mouse
라면 모든 경우의 수를 추가하여 인스턴스 타입을 체크해야 한다.동물 클래스들이
Animal
을 상속받게 하여 getOut
의 매개변수를 Animal
로 지정하여 문지기가 할 일을 도와줄 수 있다.
// 전략 인터페이스
interface Strategy {
void execute(Animal a);
}
// 구체적인 전략 1: 소리 지르기
class ShoutStrategy implements Strategy {
public void execute(Animal a) {
System.out.println("Shouting at " + a.getName() + " to get out!");
}
}
// 구체적인 전략 2: 달리기
class RunStrategy implements Strategy {
public void execute(Animal a) {
System.out.println("Chasing " + a.getName() + " out!");
}
}
// Animal 클래스 (예시와 동일)
public abstract class Animal {
abstract String getName();
}
public class Mouse extends Animal {
private String name = "쥐";
public String getName() {
return name;
}
}
public class Tiger extends Animal {
private String name = "호랑이";
public String getName() {
return name;
}
}
// Doorman 클래스가 전략을 받아들일 수 있도록함
public class Doorman {
private Strategy strategy;
public Doorman(Strategy strategy) {
this.strategy = strategy;
}
public void getOut(Animal a) {
strategy.execute(a);
}
}
// 실행 예시
public class App {
public static void main(String[] args) {
Mouse m1 = new Mouse();
Tiger t1 = new Tiger();
// 소리 지르기 전략 사용
Doorman d1 = new Doorman(new ShoutStrategy());
d1.getOut(m1);
d1.getOut(t1);
// 달리기 전략 사용
Doorman d2 = new Doorman(new RunStrategy());
d2.getOut(m1);
d2.getOut(t1);
}
}
Share article