커맨드 패턴
실행할 요청을 객체로 만들어 호출 시점과 실행 시점을 나누는 행위 패턴.
· 마지막 업데이트: 2026-11-07 · 10 min read
개요
버튼을 누른 즉시 편집하지 않고 작업을 큐에 쌓아 두었다가 순서대로 실행하는 경우가 있다. 그때는 메서드 이름만이 아니라 어떤 대상에 어떤 값을 보낼지까지 함께 보관해야 한다. 메서드를 부르면 실행이 바로 끝난다. 큐에 넣을 요청은 값으로 남지 않는다.
대상과 인자를 한 객체에 담으면 큐는 순서만 관리하고, 호출부는 실행 시점을 고른다. 커맨드(Command)는 요청을 객체로 표현하는 패턴이다. 실행 대상은 수신자(Receiver), Execute()를 호출하는 쪽은 호출자(Invoker)라 부르며, 여기서는 편집 버퍼와 명령 큐가 각각 그 역할을 맡는다.
UML
CommandQueue가 보관하는 것은 ICommand뿐이다. AppendText는 TextBuffer와 추가할 문자열을 필드로 가지며, Execute()가 호출되면 버퍼의 Append()를 실행한다. 실제 편집은 버퍼가 하고, 명령은 대상과 인자를 들고 있다가 실행을 요청받는다.
역사
GoF는 1994년 Design Patterns에서 Command를 행위 패턴으로 정리했다. 요청을 객체로 만들어 대기열이나 실행 이력 같은 구조에서 다룰 수 있게 한다.1
사용자 동작을 함수 호출로 즉시 흘려보내지 않고 객체로 실체화(reification)해 메뉴·단축키·다단계 실행 취소(Undo/Redo) 이력으로 다룬 선구적 구현은 1980년대 후반 Apple의 MacApp과 John Vlissides·Mark Linton이 설계한 Unidraw 그래픽 편집 프레임워크, 그리고 ET++의 Command 클래스였다.2
왜 사용하는가?
큐는 각 명령이 어떤 편집을 수행하는지 알지 못한 채 실행 순서만 관리한다. 편집 종류가 늘어도 큐가 맡은 일은 그대로다. 호출부에서는 작업 객체를 만드는 시점과 그것을 실행하는 시점을 따로 둘 수 있다.
명령을 객체로 감쌌다고 해서 실행 취소나 중복 방지가 저절로 따라오는 것은 아니다. 패턴이 정해 주는 몫은 요청을 객체로 만드는 데까지다. 실행 취소에는 되돌릴 상태나 역연산이 필요하고, 외부에 효과를 내는 명령이라면 재실행 정책을 별도로 정해야 한다.
예제
텍스트 추가 요청 하나를 객체로 만들어 실행하는 것으로 시작한다. 분리는 여기서 드러난다.
using System;
using System.Collections.Generic;
using System.Linq;
var buffer = new TextBuffer();
ICommand command = new AppendText(buffer, "A");
command.Execute();
Console.WriteLine(buffer.Text);
sealed class TextBuffer
{
public string Text { get; private set; } = "";
public void Append(string value) => Text += value;
}
interface ICommand { void Execute(); }
// 나중에 실행할 수 있도록 실제 대상과 인자를 명령 객체에 함께 보관한다.
sealed class AppendText(TextBuffer buffer, string value) : ICommand
{
public void Execute() => buffer.Append(value);
}
// 큐는 편집 내용을 몰라도 공통 execute 약속으로 실행 순서를 관리한다.
sealed class CommandQueue
{
private readonly Queue<ICommand> commands = new();
public void Add(ICommand command) => commands.Enqueue(command);
public void RunAll()
{
while (commands.TryDequeue(out var command)) command.Execute();
}
}
AAppendText 안에는 실행할 버퍼와 추가할 문자열이 함께 들어 있다.
확장 예제
이번에는 명령 두 개를 큐에 넣는다. 넣는 것만으로는 버퍼가 비어 있다가, RunAll()을 호출한 뒤에야 순서대로 반영된다. 만드는 일과 실행하는 일이 이렇게 갈린다.
using System;
using System.Collections.Generic;
using System.Linq;
var buffer = new TextBuffer();
var queue = new CommandQueue();
queue.Add(new AppendText(buffer, "A"));
queue.Add(new AppendText(buffer, "B"));
Console.WriteLine("before: [" + buffer.Text + "]");
queue.RunAll();
Console.WriteLine("after: [" + buffer.Text + "]");
sealed class TextBuffer
{
public string Text { get; private set; } = "";
public void Append(string value) => Text += value;
}
interface ICommand { void Execute(); }
// 나중에 실행할 수 있도록 실제 대상과 인자를 명령 객체에 함께 보관한다.
sealed class AppendText(TextBuffer buffer, string value) : ICommand
{
public void Execute() => buffer.Append(value);
}
// 큐는 편집 내용을 몰라도 공통 execute 약속으로 실행 순서를 관리한다.
sealed class CommandQueue
{
private readonly Queue<ICommand> commands = new();
public void Add(ICommand command) => commands.Enqueue(command);
public void RunAll()
{
while (commands.TryDequeue(out var command)) command.Execute();
}
}
before: []
after: [AB]이 큐는 메모리 안에서 동기적으로 동작한다. 저장이나 장애 복구, 명령 실패 뒤의 재개는 구현되어 있지 않으며, 같은 AppendText를 다시 실행하면 문자열도 그만큼 다시 추가된다.
TypeScript 예제
버퍼가 실제 편집을 수행하고, AppendText는 대상과 인자를 보관하며, 큐는 실행 순서를 담당한다. 역할을 이렇게 나누면 요청을 만드는 시점과 편집이 일어나는 시점을 어긋나게 배치할 수 있다. 세 역할이 한 클래스에 뭉치면 실행 시점을 옮길 여지가 사라진다.
class TextBuffer {
#text = "";
get text(): string { return this.#text; }
append(value: string): void { this.#text += value; }
}
interface ICommand { execute(): void; }
// 나중에 실행할 수 있도록 실제 대상과 인자를 명령 객체에 함께 보관한다.
class AppendText implements ICommand {
constructor(private readonly buffer: TextBuffer, private readonly value: string) {}
execute(): void { this.buffer.append(this.value); }
}
// 큐는 편집 내용을 몰라도 공통 execute 약속으로 실행 순서를 관리한다.
class CommandQueue {
private readonly commands: ICommand[] = [];
add(command: ICommand): void { this.commands.push(command); }
runAll(): void {
for (;;) {
const command = this.commands.shift();
if (command === undefined) return;
command.execute();
}
}
}
const buffer = new TextBuffer();
const queue = new CommandQueue();
queue.add(new AppendText(buffer, "A"));
queue.add(new AppendText(buffer, "B"));
console.log("before: " + buffer.text);
queue.runAll();
console.log("after: " + buffer.text);before:
after: AB등록하는 것만으로는 버퍼가 바뀌지 않는다. 메모리 안에서 도는 동기 큐이고, 실행 취소나 장애 뒤 재개, 중복 실행 방지는 넣지 않았다.
명령과 수신자를 연결하는 Command<TReceiver>
명령 객체는 실행할 내용을 보관하고, 수신자는 그 일이 바꾸는 객체다. 역할이 둘로 나뉘어 있으니, 어느 쪽 타입을 명령에 묶을지 정할 수 있다. ICommand<TReceiver>로 수신자 타입을 정하면 Counter에 더하는 명령을 다른 종류의 객체에 잘못 보내는 호출을 타입 검사에서 걸러낼 수 있다.
AddCommand를 만드는 순간에는 숫자가 바뀌지 않는다. Invoker.ExecuteCommand()에 명령과 수신자를 넘길 때 ExecuteCommand()가 호출되고 그제야 수신자의 값이 바뀐다. 만들기와 실행하기 사이에 시간을 둘 수 있다. 패턴 이름이 코드에 보이도록 Invoker와 Command라는 역할명을 그대로 두었다.
C#
using System;
var counter = new Counter();
ICommand<Counter> command = new AddCommand(5);
Console.WriteLine(counter.Value);
new Invoker<Counter>().ExecuteCommand(command, counter);
Console.WriteLine(counter.Value);
// TYPES
interface ICommand<TReceiver> { void ExecuteCommand(TReceiver receiver); }
sealed class Invoker<TReceiver>
{
public void ExecuteCommand(ICommand<TReceiver> command, TReceiver receiver)
=> command.ExecuteCommand(receiver);
}
sealed class Counter
{
public int Value { get; private set; }
public void Add(int value) { Value += value; }
}
sealed class AddCommand : ICommand<Counter>
{
private readonly int amount;
public AddCommand(int amount) { this.amount = amount; }
// 명령은 추가할 양을 보관하고 실행 때 받은 수신자에게 일을 맡긴다.
public void ExecuteCommand(Counter receiver) => receiver.Add(amount);
}0
5TypeScript
interface Command<TReceiver> { executeCommand(receiver: TReceiver): void; }
class Invoker<TReceiver> {
executeCommand(command: Command<TReceiver>, receiver: TReceiver): void {
command.executeCommand(receiver);
}
}
class Counter {
#value = 0;
get value(): number { return this.#value; }
add(value: number): void { this.#value += value; }
}
class AddCommand implements Command<Counter> {
constructor(private readonly amount: number) {}
// 생성할 때 저장한 요청을 실행 시점의 수신자에게 적용한다.
executeCommand(receiver: Counter): void { receiver.add(this.amount); }
}
const counter = new Counter();
const command: Command<Counter> = new AddCommand(5);
console.log(counter.value);
new Invoker<Counter>().executeCommand(command, counter);
console.log(counter.value);0
5이 명령은 실행할 때마다 값을 더한다. 실행 시점을 분리하는 것과 중복 실행을 막는 것은 다른 요구이므로, 재시도나 네트워크 전달을 붙일 때에는 별도로 중복 처리 규칙을 정한다. 같은 명령을 두 번 넘기면 값도 두 번 바뀐다.
타입 매개변수와 라이브러리 계약의 문법은 공식 문서에서 확인할 수 있다.3
일급 함수(클로저)와의 경계와 외부 부수 효과의 취소·보상
C#의 Action 델리게이트나 TypeScript의 화살표 함수(() => buffer.append("a"))처럼 현대 언어는 클로저(closure)를 기본 지원한다. 단순히 “나중에 실행할 동작 하나를 넘긴다”는 목적만 놓고 보면 클로저 자체가 이미 수신자와 인자를 캡처한 경량 커맨드이므로 굳이 ICommand 클래스를 따로 만들 필요가 없다. 전용 커맨드 클래스가 진짜 가치를 발휘하는 지점은 동작 하나에 두 개 이상의 생명주기 연산이나 메타데이터가 붙을 때다. 예를 들어 실행(Execute)과 실행 취소(Undo)를 한 쌍으로 묶거나, 큐에 쌓인 명령들을 직렬화해 디스크 로그에 남기거나, 명령마다 식별자·권한·우선순위를 조회해 병합·취소해야 할 때는 불투명한 함수 클로저 대신 명시적인 커맨드 객체가 필요하다.
또한 실행 취소(Undo)를 설계할 때는 메모리 안의 편집 상태를 되돌리는 일과 외부 세계에 이미 나간 부수 효과를 엄격히 구분해야 한다. 텍스트 버퍼에 덧붙인 문자열은 이전 길이를 기억해 두거나 메멘토 패턴 스냅샷으로 깨끗이 지울 수 있지만, 이미 발송된 이메일이나 외부 결제 게이트웨이 승인 요청은 메모리 변수를 되돌린다고 취소되지 않는다. 외부 시스템과 맞물리는 명령 큐에서는 역연산 대신 취소 전문을 새로 보내는 보상 트랜잭션(compensating action)과, 네트워크 재시도 시 같은 명령이 두 번 적용되지 않게 막는 멱등성 키 설계가 반드시 함께 들어가야 한다.
같이 보기
각주
- Gamma, Helm, Johnson, Vlissides. Design Patterns (1994). 출판사 서지. 행위 패턴의 Command 항목. ↩
- John M. Vlissides, Mark A. Linton, "Unidraw: A Framework for Building Domain-Specific Graphical Editors," ACM Transactions on Information Systems 8(3), 1990, pp. 237–268. DOI. ↩
- C# generics; TypeScript generics ↩