
"헤드 퍼스트 디자인 패턴(개정판)"을 읽고 정리한 내용입니다.
6. 호출 캡슐화하기
커맨드 패턴
커맨드 패턴(Command Pattern)은 요청을 객체로 캡슐화하여 다른 객체들을 다양한 요청에 따라 매개변수화 할 수있고, 요청을 큐에 넣거나 로그를 남기며, 실행 취소가 가능한 작업을 지원할 수 있게 한다.
예시
public interface Command {
public void execute();
public void undo();
}
public class NoCommand implements Command {
public void execute() { }
public void undo() { }
}
public class Light {
String location;
public Light(String location) {
this.location = location;
}
public void on() {
System.out.println(location + " light is on");
}
public void off() {
System.out.println(location + " light is off");
}
}
public class LightOnCommand implements Command {
Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
@Override
public void undo() {
light.off();
}
}
public class LightOffCommand implements Command {
Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.off();
}
@Override
public void undo() {
light.on();
}
}
public class RemoteControlWithUndo {
Command[] onCommands;
Command[] offCommands;
Command undoCommand;
public RemoteControlWithUndo() {
onCommands = new Command[7];
offCommands = new Command[7];
Command noCommand = new NoCommand();
for (int i = 0; i < 7; i++) {
onCommands[i] = noCommand;
offCommands[i] = noCommand;
}
undoCommand = noCommand;
}
public void setCommand(int slot, Command onCommand, Command offCommand) {
onCommands[slot] = onCommand;
offCommands[slot] = offCommand;
}
public void onButtonWasPushed(int slot) {
onCommands[slot].execute();
undoCommand = onCommands[slot];
}
public void offButtonWasPushed(int slot) {
offCommands[slot].execute();
undoCommand = offCommands[slot];
}
public void undoButtonWasPushed(int slot) {
undoCommand.undo();
}
}
public class RemoteLoader {
public static void main(String[] args) {
RemoteControlWithUndo remoteControlWithUndo = new RemoteControlWithUndo();
Light livingRoomLight = new Light("Living Room");
Light kitchenLight = new Light("Kitchen");
LightOnCommand livingRoomLightOn = new LightOnCommand(livingRoomLight);
LightOffCommand livingRoomLightOff = new LightOffCommand(livingRoomLight);
LightOnCommand kitchenLightOn = new LightOnCommand(kitchenLight);
LightOffCommand kitchenLightOff = new LightOffCommand(kitchenLight);
remoteControlWithUndo.setCommand(0, livingRoomLightOn, livingRoomLightOff);
remoteControlWithUndo.setCommand(1, kitchenLightOn, kitchenLightOff);
remoteControlWithUndo.onButtonWasPushed(0);
remoteControlWithUndo.offButtonWasPushed(0);
remoteControlWithUndo.undoButtonWasPushed(0);
remoteControlWithUndo.onButtonWasPushed(1);
remoteControlWithUndo.offButtonWasPushed(1);
remoteControlWithUndo.undoButtonWasPushed(1);
}
}
// Output
Living Room light is on
Living Room light is off
Living Room light is on
Kitchen light is on
Kitchen light is off
Kitchen light is on