← Back to scenarios
ScenarioCatalog DB

Game save memento

Store game save points so players can restore progress later.

Problem

A game must capture and restore progress checkpoints without allowing save-management code to depend on or modify the internal state representation of game objects.

Related patterns

Implementations

Memento

TypeScriptApplication

Memento in TypeScript

Captures editor content snapshots so a history manager can restore earlier document states without exposing editor internals.

TypeScript
class EditorMemento {
  constructor(readonly content: string) {}
}

class TextEditor {
  private content = "";

  write(text: string) {
    this.content = text;
  }

  createMemento() {
    return new EditorMemento(this.content);
  }

  restore(memento: EditorMemento) {
    this.content = memento.content;
  }

  print() {
    console.log(this.content);
  }
}

class History {
  private readonly snapshots: EditorMemento[] = [];

  save(memento: EditorMemento) {
    this.snapshots.push(memento);
  }

  undo(): EditorMemento | undefined {
    return this.snapshots.pop();
  }
}

const editor = new TextEditor();
const history = new History();

editor.write("Draft version");
history.save(editor.createMemento());

editor.write("Published version");
editor.print();

const previousVersion = history.undo();

if (previousVersion) {
  editor.restore(previousVersion);
}

editor.print();

Associated technologies