명령의 객체화
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 pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations.
Implementation

Sender
(akaInvoker
) - 요청을 시작할 책임을 지닌다. 하나의Command
객체의 참조를 필드로 가지고 있어야함. 보통 클라이언트가Command
객체를 만들어서 생성자로 주입한다.
Command
- 커맨드 인터페이스는 일반적으로 커맨드 실행을 위한 메서드 하나를 가진다.
CommandN
- 다양한 명령을 구현한다.
Receiver
- 클라이언트로 부터 명령을 수신 받는다.
Client
- 명령 객체의 생성자로 요청 파라미터, 수신 인스턴스를 사용해 구체 명령 객체를 생성한다. 생성된 명령 객체는Invoker
에 의해 활용된다.
Applicablity
- Operation을 객체로 파라미터 화 하고 싶을때 사용하자.
- Operation을 Queing 하여 Scheduling 하고 싶을때 사용하자.
Undo/Redo
기능을 구현하고 싶을때 활용하자.- see also Memento Pattern
Examples
Here are some examples of Commands in core Java libraries:
- All implementations of
java.lang.Runnable
- All implementations of
javax.swing.Action
public interface Command { void execute(); }
import java.util.LinkedList; import java.util.List; public class Main { public static void main(String[] args) { List<Command> list = new LinkedList<>(); list.add(() -> System.out.println("Task 1")); list.add(() -> System.out.println("Task 2")); list.add(() -> System.out.println("Task 3")); for (Command command : list) { command.execute(); } } }
public class StringPrintCommand implements Command{ String str; public StringPrintCommand(String str) { this.str = str; } @Override public void execute() { System.out.println(str); } @Override public int compareTo(Command o) { return str.compareTo(((StringPrintCommand)o).str); } }
import java.util.PriorityQueue; public class Main { public static void main(String[] args) { PriorityQueue<Command> list = new PriorityQueue<>(); list.add(new StringPrintCommand("B")); list.add(new StringPrintCommand("A")); list.add(new StringPrintCommand("C")); for (Command command : list) { command.execute(); } } }
Relations with Other Patterns
- Chain of Responsibility Pattern, Command Pattern Mediator Pattern, Observer Pattern 는 모두 요청을 다루는 Sender와 Receiver를 연결하는 방법을 다룬다.
- Cahin of Resposibility - 요청을 Chain에게 전달하여 처리 할 수 있을때 까지 전달함
- Command - Sender와 Receivers를 단방향으로 연결한다.
- Mediator - 중간에
Mediator
를 두어Colleague
(Sender)와Colleague
(Receivers) 간의 Coupling을 제거한다. - Observer -
Subscriber
(Receivers) 가 동적으로 전달받을 객체를 subscribe/ unsubscribe 할 수 있게한다.
- Chain of Responsibilty 패턴의
Handlers
는 Command 패턴으로 구현할 수 있다.
- Command 패턴과 Memento 패턴을 함께 사용해 “undo”기능을 구현할 수 있다.
- Command 패턴과 Strategy 패턴은 Action을 담은 객체를 파라미터화 한다는 점에서 비슷하다. 하지만 전략패턴은 같은 명령에 대해 다른 알고리즘을 제공하고 명령 패턴은 아예 명령 자체를 파라미터화 한다는 것이 다르다.
- Visitor 패턴은 Command 패턴의 Powerful version이라고 할 수 있다.