명령, 수신자, 호출자로 구성된다.
public class Light {
public void turnOn() {
System.out.println("Light on");
}
public void turnOff() {
System.out.println("Light off");
}
}
우선 제일 만만한 수신자 Light 이다.
receiver는 command의 구현체를 구현할 때 필요한 클래스이다.
public interface Command {
void execute();
}
public class TurnOnCommand implements Command {
private Light light;
public TurnOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
this.light.turnOn();
}
}
public class TurnOffCommand implements Command {
private Light light;
public TurnOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
this.light.turnOff();
}
}
command 클래스와 그 구현체(Concrete command) 이다.
커맨드는 실행될 기능에 대한 인터페이스이다.
public class Switcher {
public List<Command> commands;
public Switcher() {
this.commands = new ArrayList<>();
}
public void addCommand(Command command) {
this.commands.add(command);
}
public void executeCommand() {
for (Command command : commands) {
command.execute();
}
}
}
호출자(invoker)는 기능을 호출하는 클래스이다. (command.execute()
)
만약 커맨드가 없고 receiver와 invoker 밖에 없었다면 invoker는 receiver의 모든 메서드를 알아야하고 (강한 결합), 새로운 receiver가 추가되어 확장된다면 receiver, invoker 코드 모두 고쳐야 한다.(OCP 위반)