의도 :
⇒ 재사용성 증가
⇒ 호출자와 수신자 클래스 사이의 의존성 제거
다른 이름 :
참여자 :
예제 :
package command;
public interface Command {
public abstract void execute();
}
package command;
public class Button {
private Command theCommand;
public Button(Command theCommand) {
setCommand(theCommand);
}
public void setCommand(Command newCommand) {
this.theCommand = newCommand;
}
public void pressed() {
theCommand.execute();
}
}
package command;
public class Lamp {
public void turnOn() {
System.out.println("Lamp on");
}
}
package command;
public class LampOnCommand implements Command{
private Lamp theLamp;
public LampOnCommand(Lamp theLamp) {
this.theLamp = theLamp;
}
public void execute() {
theLamp.turnOn();
}
}
package command;
public class Alarm {
public void start() {
System.out.println("Alarming");
}
}
package command;
public class AlarmStartCommand implements Command {
private Alarm theAlarm;
public AlarmStartCommand(Alarm theAlarm) {
this.theAlarm = theAlarm;
}
public void execute() {
theAlarm.start();
}
}
package command;
public class Client {
public static void main(String[] args) {
Lamp lamp = new Lamp();
Command lampOnCommand = new LampOnCommand(lamp);
Alarm alarm = new Alarm();
Command alarmStartCommand = new AlarmStartCommand(alarm);
Button button1 = new Button(lampOnCommand);
button1.pressed();
Button button2 = new Button(alarmStartCommand);
button2.pressed();
button2.setCommand(lampOnCommand);
button2.pressed();
}
}
Lamp on
Alarming
Lamp on
동기 :
활용성 :