PYTHON · 디자인패턴
커맨드 패턴
커맨드 패턴으로 요청을 객체로 캡슐화하여 실행, 취소, 재실행을 지원합니다.
디자인패턴고급command커맨드undo디자인패턴
핵심 설명
커맨드 패턴으로 요청을 객체로 캡슐화하여 실행, 취소, 재실행을 지원합니다.
Python code
from abc import ABC, abstractmethod
class Command(ABC):
@abstractmethod
def execute(self) -> None: ...
@abstractmethod
def undo(self) -> None: ...
class TextEditor:
def __init__(self):
self.content = ""
def __repr__(self):
return f'TextEditor("{self.content}")'
class InsertCommand(Command):
def __init__(self, editor: TextEditor, text: str):
self.editor = editor
self.text = text
def execute(self):
self.editor.content += self.text
def undo(self):
self.editor.content = self.editor.content[:-len(self.text)]
class DeleteCommand(Command):
def __init__(self, editor: TextEditor, count: int):
self.editor = editor
self.count = count
self.deleted = ""
def execute(self):
self.deleted = self.editor.content[-self.count:]
self.editor.content = self.editor.content[:-self.count]
def undo(self):
self.editor.content += self.deleted
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:
cmd = self._history.pop()
cmd.undo()
editor = TextEditor()
history = CommandHistory()
history.execute(InsertCommand(editor, "Hello"))
history.execute(InsertCommand(editor, " World"))
print(editor) # "Hello World"
history.execute(DeleteCommand(editor, 6))
print(editor) # "Hello"
history.undo()
print(editor) # "Hello World"
history.undo()
print(editor) # "Hello"학습 팁
커맨드 패턴은 Undo/Redo, 매크로 기록, 트랜잭션 등에 활용됩니다.
주의할 점
undo()에서 상태 복원이 불완전하면 데이터 정합성이 깨집니다. 모든 커맨드의 undo를 철저히 테스트하세요.
자주 묻는 질문
커맨드 패턴란 무엇인가요?
커맨드 패턴으로 요청을 객체로 캡슐화하여 실행, 취소, 재실행을 지원합니다.
커맨드 패턴 학습 시 주의할 점은 무엇인가요?
undo()에서 상태 복원이 불완전하면 데이터 정합성이 깨집니다. 모든 커맨드의 undo를 철저히 테스트하세요.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.