JAVA/DesignPattern

Design Pattern 디자인 패턴 Command Pattern 커맨드 패턴

호두밥 2021. 12. 22. 21:30

Command Pattern 커맨드 패턴

행동 패턴으로, 요청을 커맨드 객체로 감싸서, 요청 객체에게 전달합니다. 요청 객체는 요청(명령)을 처리할 적잘한 객체를 찾아 명령을 전달합니다. 

Command Pattern 커맨드 패턴이 적합한 경우

  • 객체의 작업을 파라미터화 하고 싶을 때 
  • 객체의 작업을 queue로 관리하고 싶을때 (작업을 스케쥴링하고 싶을 때)
  •  되돌릴 수 있는 작업을 구현하고 싶을 때 (Redo, Undo)
    • 작업의 이력을 STACK 방식으로 기록해두고 사용할 수 있습니다. 작업을 되돌리고 싶을 때, 현재 상태에 지정된 되돌리는 작업 (reverseOperation)을 수행하면 됩니다.
    • Memento Pattern

장단점

장점

  • 작업 요청과 수행을 분리할 수 있습니다. (단일책임원칙)
  • 기존 코드를 수정하지 않고도 새로운 작업(명령)을 추가할 수 있습니다. (개방/폐쇄원칙)
  • Undo/Redo 기능을 적용할 수 있습니다.
  • 작업의 후처리를 정의할 수 있습니다.
  • 몇개의 작업 그룹을 지정할 수 있습니다.

단점

  • 명령을 보내고 받는 새로운 계층을 정의하려고 한다면 코드가 복잡해질 수 있습니다.

Command Pattern 커맨드 패턴 구현

Document

public class Document {
    public void print(){
        System.out.println("print");
    }
    public void save(){
        System.out.println("save");
    }
    public void open(){
        System.out.println("open");
    }
}

Command

public interface Command {
    void execute();
}

OpenCommand

public class OpenCommand implements Command {
    private Document document;

    public OpenCommand(Document doc) {
        this.document = doc;
    }

    @Override
    public void execute() {
        document.open();;
    }
}

PrintCommand

public class PrintCommand implements Command {
    private Document document;

    public PrintCommand(Document document) {
        this.document = document;
    }

    @Override
    public void execute() {
        document.print();;
    }
}

SaveCommand

public class SaveCommand implements Command {
    private Document dosc;

    public SaveCommand(Document dosc) {
        this.dosc = dosc;
    }

    @Override
    public void execute() {
        dosc.save();;
    }
}

CommandReceiver

public class CommandReceiver {
    Command command;

    public void setCommand(Command command) {
        this.command = command;
    }

    public void execute(){
        command.execute();
    }
}

Main

public class Main {
    public static void main(String[] args) {
        CommandReceiver receiver = new CommandReceiver();
        Document document = new Document();
        receiver.setCommand(new OpenCommand(document));
        receiver.execute();
        receiver.setCommand(new PrintCommand(document));
        receiver.execute();
    }
}
open
print

 

참조