여러 알고리즘을 개별 클래스로 추상화하고 공통 인터페이스로 로직을 수행하도록 코드를 바꾸지 않고 알고리즘을 변경하는 방법
Comparator
가 대표적이다.
여러 알고리즘을 캡슐화하고 상호 교환 가능하게 하는 패턴. Context
에서 사용할 알고리즘을 클라이언트가 선택한다.
public class BluLightRedLight {
private int speed;
public BlueLightRedLight(int speed) {
this.speed = speed;
}
public void blueLight() {
if(speed == 1) {
//log
} else if(speed = 2) {
//log
}
}
public void redLight() {
//log
}
}
public class Client {
public static void main(String[] args) {
BlueLightRedLight blueLightRedLight = new BlueLightRedLight(2);
blueLightRedLight.blueLight();
blueLightRedLight.redLight();
}
}
public class BlueLightRedLight {
private Speed speed;
public BlueLightRedLight(Speed speed) {
this.speed = speed;
}
public void blueLight() {
speed.blueLight();
}
public void redLight() {
speed.redLight();
}
}
public interface Speed {
void blueLight();
void redLight();
}
public class Normal implements Speed {
@Override
public void blueLight() {
//log
}
@Override
public void redLight() {
}
}
public class Client {
public static void main(String[] args) {
BlueLightRedLight game = new BlueLightRedLight(new Normal());
game.blueLight(new Normal());
game.blueLight(new Faster());
}
}
Collections.sort(numbers, new comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
}};