#6BehavioralMedium

커맨드 패턴 (Editor Undo/Redo)

커맨드 패턴

커맨드 패턴을 사용해 실행과 취소를 캡슐화한 Command 인터페이스와 명령 히스토리를 관리하는 EditorHistory를 구현하세요.

각 명령은 do()undo()를 가지며, EditorHistory는 done-스택과 redo-스택을 유지합니다.

API

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

export class EditorHistory {
  execute(cmd: Command): void; // cmd.do() 호출 후 done에 push, redo 스택 비움
  undo(): boolean;             // 되돌릴 명령이 있으면 true, 없으면 false
  redo(): boolean;             // 다시 할 명령이 있으면 true, 없으면 false
}

예시

const h = new EditorHistory();
h.execute(cmd1);
h.execute(cmd2);
h.undo();  // cmd2.undo() 호출
h.redo();  // cmd2.do() 다시 호출

학습 포인트

  • 행위와 그 역연산을 객체로 캡슐화
  • 호출자는 구체 명령을 모르고 인터페이스만 의존
  • 새 명령 실행 시 redo 스택은 항상 비움
언어: