본문 바로가기
Theory/Design Pattern

Command Pattern

by y.j 2022. 5. 12.
728x90

Command Pattern

request를 object로 캡슐화 한 다음 캡슐화된 object를 다른 요청이나 큐 등 다른 operation의 파라미터로 사용하게 하는 것이다. 

request의 요청자와 요청간의 결합을 어떻게 회피 할 수 있을까?
어떻게 특정 object를 request의 환경이 될 수 있도록 할까?

 

 

compile-time에 request의 요청자와 특정 request를 결합시켜버린다면 run-time에는 request를 명시하는 것이 어렵다. 특정 operation을 명시하고 싶을 때 하드코딩을 회피해야 한다. 그렇게 한다면 compile-time과 run-time에 요청 처리에 대한 변화를 주기 쉬워진다.

 

Solution

Receiver1은 Reuqest, Command는 Reciever의 요청을 수행해주는 interface, Invoker는 request를 처리해주는 class이다. Invoker는 Command의 execute()를 통해 Receiver의 action을 수행하게 한다. 이러한 구조의 장점은 Invoker가 수행해야할 command가 수정되거나 추가될 수 있고, Request도 다양하게 올 수 있다. 하지만 서로 개방폐쇄의 원칙을 지키고 있기 유동적으로 수정하거나 바뀔 수 있다.

public class Invoker {
    private Command command;
    public Invoker(Command command) {
        this.command = command;
    }
    public void operation() {
        System.out.println("Invoker : Calling execute on the installed command ...");
        command.execute();
    }
}

 

public class Command1 implements Command{

    private Receiver1 receiver1;
    public Command1(Receiver1 receiver1) {
        this.receiver1 = receiver1;
    }

    @Override
    public void execute() {
        System.out.println("Command1 : Performing (carrying out) the request.");
        receiver1.action1();
    }
}

 

public class Receiver1 {
    public void action1() {
        System.out.println("Receiver1 : Hello World!");
    }
}

Test Code : run-time에 Receiver1을 바꿔주거나 command를 바꿔주면 유동적으로 처리 할 수 있다.

public class CommandPatternTest {

    @Test
    public void commandPatternTest() {
        Command command = new Command1(new Receiver1());
        Invoker invoker = new Invoker(command);

        invoker.operation();
    }
}

 

Advantages

• 새로운 command를 추가하기 쉽다.

• command를 교체하기 쉽다.

 - run-time에 command를 교환하거나 다양한 request에 대한 필요한 command를 만들기 쉽다.


Disadvantages

• 추가적인 level이 필요하다.

 - command와 request를 분리할 추가적인 interface나 class가 필요하다.

 

[전체코드]

https://github.com/jKyounju/adapterPatterns/tree/master/src/BehavioralPattern/CommandPattern

728x90

'Theory > Design Pattern' 카테고리의 다른 글

Iterator Pattern  (0) 2022.05.15
Interpreter Pattern  (0) 2022.05.14
Chain Of Responsibility Pattern  (0) 2022.05.10
Flyweight Pattern  (0) 2022.05.09
Facade Pattern  (0) 2022.05.09

댓글