본문 바로가기
디자인 패턴

자바(JAVA) - 커맨드(Command) 패턴

by Hyeongjun_Ham 2023. 11. 1.

1. 의도

요청 / 명령을 객체로 캡슐화하고 이를 매개변수화하여 다양한 요청 / 명령을 처리하거나 연기할 수 있도록 하는 행위 패턴

 

2. 용도

요청 / 명령을 객체화하여 매개변수화 하려는 경우 사용되는 행위 패턴

즉, 요청 / 명령들을 메서드 인수로 전달하고, 이들을 다른 객체의 내부에 저장 및 런타임에 연결된 요청 / 명령들을 전환하는 등 여러 작업을 할 수 있다.

 

3. UML

 

4. 구현

public interface ICommand {
    void execute();
}
==============================================================
public class Light {
    public void turnOn() {
        System.out.println("Light turn on");
    }

    public void turnOff() {
        System.out.println("Light turn off");
    }
}
==============================================================
public class LightTurnOnCommand implements ICommand{

    private Light light;

    public LightTurnOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOn();
    }
}
==============================================================
public class LightTurnOffCommand implements ICommand {

    private Light light;

    public LightTurnOffCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOff();
    }
}
==============================================================
//invoker Class
public class RemoteControl {

    private final List<ICommand> commandList = new ArrayList<>();

    public void addCommand(ICommand command) {
        commandList.add(command);
    }

    public void execute(int index) {
        if (index >= 0 && index < commandList.size()) {
            commandList.get(index).execute();
        }
    }
}
==============================================================
public class Client {
    public static void main(String[] args) {
        Light light = new Light();
        LightTurnOnCommand lightTurnOnCommand = new LightTurnOnCommand(light);
        LightTurnOffCommand lightTurnOffCommand = new LightTurnOffCommand(light);
        
        RemoteControl remoteControl = new RemoteControl();
        remoteControl.addCommand(lightTurnOnCommand);
        remoteControl.addCommand(lightTurnOffCommand);

        remoteControl.execute(0); // turn on
        remoteControl.execute(1); // turn off
    }
}

 

예를 들어 PowerOn 명령을 추가한다면

 

public class PowerOnCommand implements ICommand{
    @Override
    public void execute() {
        System.out.println("power on");
    }
}
public class Client {
    public static void main(String[] args) {
        Light light = new Light();
        LightTurnOnCommand lightTurnOnCommand = new LightTurnOnCommand(light);
        LightTurnOffCommand lightTurnOffCommand = new LightTurnOffCommand(light);

        PowerOnCommand powerOnCommand = new PowerOnCommand();

        RemoteControl remoteControl = new RemoteControl();
        remoteControl.addCommand(lightTurnOnCommand);
        remoteControl.addCommand(lightTurnOffCommand);
        remoteControl.addCommand(powerOnCommand);

        remoteControl.execute(0); // turn on
        remoteControl.execute(1); // turn off
        remoteControl.execute(2); // power on
    }

}

 

간단하게 추가 가능하다.

 

5. 패턴의 장단점

  • 장점
    • 요청 / 명령을 객체로 캡슐화하여 다양하게 실행하고 연기하거나 취소하기 쉽다.
    • 요청 / 명령의 호출자(Invoker)와 수신자(Receiver)를 분리하여 느슨한 결합도를 유지한다.
    • 새로운 요청 / 명령을 추가하기 쉽고, 기존 요청 / 명령을 수정하거나 제거하기 쉽다.
    • 단일 책임 원칙(SRP)을 준수한다.
    • 기존 코드의 수정이 없어 개발폐쇄원칙(OCP)을 준수한다.
  • 단점
    • 호출자(Invoker)와 수신자(Receiver) 사이에 새로운 레이어를 도입하기 때문에 코드가 복잡해질 수 있다.

 

출처 :

https://refactoring.guru/design-patterns/command

 

Command

/ Design Patterns / Behavioral Patterns Command Also known as: Action, Transaction Intent Command is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you p

refactoring.guru