여러 알고리즘을 캡슐화하고 상호 교환 가능하게 만드는 패턴


before => 행동 로직이 클래스 안에 박혀 있다.
public class BlueLightRedLight{
private int speed;
public BlueLightRedRight(int speed){
this.speed = speed;
}
public void blueLight() {
if (speed == 1) {
System.out.println("무 궁 화 꽃 이");
} else if (speed == 2) {
System.out.println("무궁화꽃이");
} else {
System.out.println("무광꼬치");
}
}
public void redLight() {
if (speed == 1) {
System.out.println("피 었 습 니 다.");
} else if (speed == 2) {
System.out.println("피었습니다.");
} else {
System.out.println("피어씀다");
}
}
}
public class Client {
public static void main(String[] args) {
BlueLightRedLight blueLightRedLight = new BlueLightRedLight(3);
blueLightRedLight.blueLight();
blueLightRedLight.redLight();
}
}
after => 행동을 바깥으로 분리해서 갈아끼울 수 있게 만든 것입니다.
public class BlueLightRedLight {
public void blueLight(Speed speed) {
speed.blueLight();
}
public void redLight(Speed speed) {
speed.redLight();
}
}
public class Client {
public static void main(String[] args) {
BlueLightRedLight game = new BlueLightRedLight();
game.blueLight(new Normal());
game.redLight(new Fastest());
game.blueLight(new Speed() {
@Override
public void blueLight() {
System.out.println("blue light");
}
@Override
public void redLight() {
System.out.println("red light");
}
});
}
}
public class Normal implements Speed {
@Override
public void blueLight() {
System.out.println("무 궁 화 꽃 이");
}
@Override
public void redLight() {
System.out.println("피 었 습 니 다.");
}
}
