컀맨λ
κ°μ
μ€νλ κΈ°λ₯μ μΊ‘μν ν¨μΌλ‘μ¨ μ£Όμ΄μ§ μ¬λ¬ κΈ°λ₯μ μ€νν μ μλ μ¬μ¬μ©μ±μ΄ λμ ν΄λμ€λ₯Ό μ€κ³νλ ν¨ν΄
μ΄λ²€νΈκ° λ°μνμλ μ€νλ κΈ°λ₯μ΄ λ€μνλ©΄μλ λ³κ²½μ΄ νμν κ²½μ°μ μ΄λ²€νΈλ₯Ό λ°μμν€λ ν΄λμ€λ₯Ό λ³κ²½νμ§ μκ³ μ¬μ¬μ©νκ³ μ ν λ μ μ©νλ€.
μ€νλ κΈ°λ₯μ μΊ‘μν ν¨μΌλ‘μ¨ κΈ°λ₯ μ€νμ μꡬνλ νΈμΆμ (Invoker) ν΄λμ€μ μ€μ κΈ°λ₯μ μ€ννλ μμ μ (Receiver) ν΄λμ€ μ¬μ΄μ μμ‘΄μ±μ μ κ±°νλ€.
λ°λΌμ μ€νλ κΈ°λ₯μ λ³κ²½μλ νΈμΆμ ν΄λμ€λ₯Ό μμ μμ΄ κ·Έλλ‘ μ¬μ©ν μ μλλ‘ ν΄μ€λ€.
μνμ λ°λ₯Έ μμ μ
- Command
- μ€νλ κΈ°λ₯μ λν μΈν°νμ΄μ€
- μ€νλ κΈ°λ₯μ execute λ©μλλ‘ μ μΈν¨
- ConcreteCommand
- μ€μ λ‘ μ€νλλ κΈ°λ₯μ ꡬν
- μ¦, Command λΌλ μΈν°νμ΄μ€λ₯Ό ꡬνν¨
- Invoker
- κΈ°λ₯ μ€νμ μμ²νλ νΈμΆμ ν΄λμ€
- Receiver
- ConcreteCommand μμ
execute()
λ©μλλ₯Ό ꡬνν λ νμν ν΄λμ€ - μ¦, ConcreteCommand μ κΈ°λ₯μ μ€ννκΈ° μν΄ μ¬μ©νλ μμ μ ν΄λμ€
- ConcreteCommand μμ
μμ
λ§λ₯λ²νΌ λ§λ€κΈ°λ₯Ό μ΄μ©νμ¬ μ»€λ§¨λ ν¨ν΄μ μ μ©ν΄λ³Έλ€.
λ²νΌμ λλ₯΄λ©΄ νΉμ ν λμνκ²λ νλ€.
Command ν΄λμ€
public interface Command {
public abstract void execute();
}
Button ν΄λμ€
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();
}
}
Lamp, LampOnCommand ν΄λμ€
public class Lamp {
public void turnOn() {
System.out.println("Lamp On");
}
}
public class LampOnCommand implements Command {
private Lamp theLamp;
public LampOnCommand(Lamp theLamp) {
this.theLamp = theLamp;
}
public void execute() {
theLamp.turnOn();
}
}
Alarm, AlarmStartCommand ν΄λμ€
public class Alarm {
public void start() {
System.out.println("Alarming");
}
}
public class AlarmStartCommand implements Command {
private Alarm theAlarm;
public AlarmStartCommand(Alarm theAlarm) {
this.theAlarm = theAlarm;
}
public void execute() {
theAlarm.start();
}
}
ν΄λΌμ΄μΈνΈ μ¬μ©μ½λ
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);
// λ¨ν μΌλ Command μ€μ
Button button1 = new Button(lampOnCommand);
// λ¨ν μΌλ κΈ°λ₯ μν
button1.pressed();
// μλ μΈλ¦¬λ Command μ€μ
Button button2 = new Button(alarmStartCommand);
// μλ μΈλ¦¬λ κΈ°λ₯ μν
button2.pressed();
// λ€μ λ¨ν μΌλ Command μ€μ
button2.setCommand(lampOnCommand);
// λ¨ν μΌλ κΈ°λ₯ μν
button2.pressed();
}
}
β μν Refactoring β