μ»€λ§¨λ“œ

κ°œμš”

싀행될 κΈ°λŠ₯을 μΊ‘μŠν™” ν•¨μœΌλ‘œμ¨ 주어진 μ—¬λŸ¬ κΈ°λŠ₯을 μ‹€ν–‰ν•  수 μžˆλŠ” μž¬μ‚¬μš©μ„±μ΄ 높은 클래슀λ₯Ό μ„€κ³„ν•˜λŠ” νŒ¨ν„΄

μ΄λ²€νŠΈκ°€ λ°œμƒν–ˆμ„λ•Œ 싀행될 κΈ°λŠ₯이 λ‹€μ–‘ν•˜λ©΄μ„œλ„ 변경이 ν•„μš”ν•œ κ²½μš°μ— 이벀트λ₯Ό λ°œμƒμ‹œν‚€λŠ” 클래슀λ₯Ό λ³€κ²½ν•˜μ§€ μ•Šκ³  μž¬μ‚¬μš©ν•˜κ³ μž ν•  λ•Œ μœ μš©ν•˜λ‹€.

Command Pattern

싀행될 κΈ°λŠ₯을 μΊ‘μŠν™” ν•¨μœΌλ‘œμ¨ κΈ°λŠ₯ μ‹€ν–‰μ˜ μš”κ΅¬ν•˜λŠ” 호좜자 (Invoker) ν΄λž˜μŠ€μ™€ μ‹€μ œ κΈ°λŠ₯을 μ‹€ν–‰ν•˜λŠ” μˆ˜μ‹ μž (Receiver) 클래슀 μ‚¬μ΄μ˜ μ˜μ‘΄μ„±μ„ μ œκ±°ν•œλ‹€.

λ”°λΌμ„œ 싀행될 κΈ°λŠ₯의 변경에도 호좜자 클래슀λ₯Ό μˆ˜μ • 없이 κ·ΈλŒ€λ‘œ μ‚¬μš©ν•  수 μžˆλ„λ‘ ν•΄μ€€λ‹€.

μ—­ν™œμ— λ”°λ₯Έ μž‘μ—…μž

  • Command
    • 싀행될 κΈ°λŠ₯에 λŒ€ν•œ μΈν„°νŽ˜μ΄μŠ€
    • 싀행될 κΈ°λŠ₯을 execute λ©”μ„œλ“œλ‘œ 선언함
  • ConcreteCommand
    • μ‹€μ œλ‘œ μ‹€ν–‰λ˜λŠ” κΈ°λŠ₯을 κ΅¬ν˜„
    • 즉, Command λΌλŠ” μΈν„°νŽ˜μ΄μŠ€λ₯Ό κ΅¬ν˜„ν•¨
  • Invoker
    • κΈ°λŠ₯ 싀행을 μš”μ²­ν•˜λŠ” 호좜자 클래슀
  • Receiver
    • ConcreteCommand μ—μ„œ execute() λ©”μ„œλ“œλ₯Ό κ΅¬ν˜„ν•  λ•Œ ν•„μš”ν•œ 클래슀
    • 즉, 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();
  }
}