디자인 패턴 (Design Pattern)

[행동 패턴] 커맨드 패턴(Command Pattern, 명령 패턴)

계란💕 2023. 2. 27. 17:38

Command Pattern(커맨드 패턴, 명령 패턴)

  • 요청을 요청에 대한 모든 정보가 포함된 독립 실행형 객체로 변환하는 행동 디자인 패턴이다. 
  • 명령이 객체화되어 있다. 
  • Command 클래스 안에는 출력할 수 있는 메서드가 포함돼있다. 
    • execute() 하면 해당하는 Command의 멤버 변수의 string 값을 출력하도록 한다. 
  • 다양한 요청들이 있는 메서드들을 인수화할 수 있도록하면 요청의 실행을 지연 또는 대기열에 넣을 수 있도록 하고 또 실행 취소할 수 있도록 작업을 지원할 수 있도록 한다.
  •  

 


예제 (1)

  • Command
<hide/>
public interface Command extends Comparable<Command>{
    void execute();
}

 

 

  • 명령을 Queue에 넣고 실행한다. 
<hide/>
public static void main(String[] args) {

    List<Command> list = new LinkedList<>();
    list.add(new Command() {
        @Override
        public void execute() {
            System.out.println("= 작업 1 =");
        }
    });

    list.add(new Command() {
        @Override
        public void execute() {
            System.out.println("= 작업 2 =");
        }
    });

    list.add(new Command() {
        @Override
        public void execute() {
            System.out.println("= 작업 3 =");
        }
    });
    for (Command command: list) {
        command.execute();
    }

}

   Note) 실행 결과

  • 명령 패턴을 사용

 


예제 (2)

  • 우선 순위 큐에 제네릭으로 Command를 담으려면 Comparable<>을 extends 해야한다. => PriorityQueue<Command>

 

  • StringPrintCommand 클래스
    • 멤버 변수인 str 을 기준으로 오름차순 정렬
<hide/>
public class StringPrintCommand implements  Command{


    protected String str;

    public StringPrintCommand(String str) {
        this.str = str;
    }
    
    @Override
    public void execute() {
        System.out.println("this.str = " + this.str );
    }

    @Override
    public int compareTo(Command o) {

        StringPrintCommand other = (StringPrintCommand) o;
        return this.str.length() - other.str.length();
    }
}

 

  • Main
    • 커맨드 패턴을 통해서 명령을 객체화한다. 
<hide/>
public static void main(String[] args) {

    PriorityQueue<Command> pq = new PriorityQueue<>();
    pq.add(new StringPrintCommand("ABC"));
    pq.add(new StringPrintCommand("ABCD"));
    pq.add(new StringPrintCommand("A"));
    pq.add(new StringPrintCommand("AB"));

    for (Command command : pq) {
        command.execute();
    }
}

  

  Note) 실행 결과

  • 연산에 관한 메서드를 오버라이드했기 때문에 (오름차순) 정렬된 상태로 원소가 뽑힌다.  

 


궁금한 점 및 기타

  • pq는 poll() 할 때만이 아니라 get() 해올 때도 정해진 우선순위대로 원소를 뽑아서 보여준다.

 

 

출처 - https://www.inflearn.com/course/lecture?courseSlug=%EC%9E%90%EB%B0%94-%EB%94%94%EC%9E%90%EC%9D%B8-%ED%8C%A8%ED%84%B4&unitId=3212