커맨드 패턴(Command Pattern)은 요청을 객체로 캡슐화해 요청의 실행, 취소(Undo), 큐잉, 로깅을 가능하게 하는 행동 패턴이다.
구조
Invoker → Command (execute/undo)
├── ConcreteCommand → Receiver
Client는 ConcreteCommand 생성 후 Invoker에 설정
python
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
class Command(ABC):
@abstractmethod
def execute(self): pass
@abstractmethod
def undo(self): pass
class TextEditor:
def __init__(self):
self.content = ""
def insert(self, text: str, pos: int):
self.content = self.content[:pos] + text + self.content[pos:]
def delete(self, pos: int, length: int):
self.content = self.content[:pos] + self.content[pos+length:]
class InsertCommand(Command):
def __init__(self, editor: TextEditor, text: str, pos: int):
self.editor = editor
self.text = text
self.pos = pos
def execute(self):
self.editor.insert(self.text, self.pos)
def undo(self):
self.editor.delete(self.pos, len(self.text))
class CommandHistory:
def __init__(self):
self._history: list[Command] = []
def execute(self, cmd: Command):
cmd.execute()
self._history.append(cmd)
def undo(self):
if self._history:
self._history.pop().undo()
editor = TextEditor()
history = CommandHistory()
history.execute(InsertCommand(editor, "Hello", 0))
history.execute(InsertCommand(editor, " World", 5))
print(editor.content) # Hello World
history.undo()
print(editor.content) # Hello
활용 사례
| 사례 | 설명 |
|---|
| 텍스트 에디터 | Undo/Redo |
| 트랜잭션 | DB 롤백 |
| 매크로 | 명령 묶음 실행 |
| 작업 큐 | 비동기 요청 처리 |
| 리모컨 | 다양한 기기 제어 |
관련 개념