만능 버튼 만들기
Command.class
public interface Command {
void execute();
}
Button.class
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();
}
}
pressed()
를 통해 실행한다Lamp.class
public class Lamp {
public void turnOn() {
System.out.println("Lamp On");
}
}
LampOnCommand.class
public class LampOnCommand implements Command {
private Lamp theLamp;
public LampOnCommand(Lamp theLamp) {
this.theLamp = theLamp;
}
public void execute() {
theLamp.turnOn();
}
}
Alarm.class
public class Alarm {
public void start(){ System.out.println("Alarming"); }
}
AlarmStartCommand.class
public class AlarmStartCommand implements Command {
private Alarm theAlarm;
public AlarmStartCommand(Alarm theAlarm) { this.theAlarm = theAlarm; }
public void execute() { theAlarm.start(); }
}
Main.class
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
참조: