#14BehavioralMedium

Command Pattern (Undo/Redo)

Command Pattern

실행과 취소를 캡슐화한 Command 인터페이스와, 명령 히스토리를 가진 Editor를 구현하세요.

API

export interface Command {
  execute(): void;
  undo(): void;
}

export class Editor {
  text: string;
  execute(cmd: Command): void;
  undo(): boolean;        // 되돌릴 게 있으면 true
  redo(): boolean;        // 다시 할 게 있으면 true
}

export class TypeCommand implements Command {
  constructor(editor: Editor, text: string);
  execute(): void;        // editor.text += text
  undo(): void;           // editor.text에서 마지막 text 제거
}

동작

  • editor.execute(cmd)는 cmd.execute()를 호출하고 history에 push, redo 스택은 비움
  • editor.undo()는 마지막 명령의 undo()를 호출하고 redo 스택에 push, 없으면 false
  • editor.redo()는 redo 스택에서 꺼내 execute()를 다시 호출, 없으면 false
  • 새 명령 실행 시 redo 스택은 항상 클리어

학습 포인트

  • 행위(execute)와 그 역연산(undo)을 객체로 캡슐화
  • 호출자(Editor)는 어떤 명령인지 모르고 인터페이스만 의존
  • undo/redo, 매크로, 큐잉, 로깅에 활용
언어: