[행동 패턴] 커맨드


명령 패턴

  • 명령이 객관화됩니다.
  • Command 클래스에는 인쇄할 수 있는 메서드가 포함되어 있습니다.
    • execute()는 해당 명령의 멤버 변수의 문자열 값을 반환합니다.

예 1)

  • 명령을 큐에 넣고 실행하십시오.
<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();
    }

}

주) 실행결과

  • 명령 패턴 사용



예 (2)

  • Comparable<>을 확장하여 일반적으로 우선순위 대기열에 명령을 추가합니다. => 우선순위 대기열

  • 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();
    }
}

  • 주로
    • 명령은 명령 패턴에 의해 객관화됩니다.
<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();
    }
}

주) 실행결과

  • 작업 방법을 재정의하므로 항목이 정렬(오름차순) 순서로 선택됩니다.



기타

  • 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