THN Interview Prep

Memento (Behavioral)

Intent / problem it solves

Capture and externalize an object’s internal state so it can be restored later without breaking encapsulation. Supports undo, checkpoints, and transactional rollbacks.

When to use / when NOT

Use for editors, games, or multi-step wizards that need reliable snapshots.

Avoid when state is huge and copying is expensive—consider event sourcing or command logs instead.

Structure

Originator creates mementos; caretaker stores them opaquely; memento hides originator details from others.

Loading diagram…

Go example

package main

import "fmt"

type EditorState struct {
	Title string
	Body  string
}

type Editor struct {
	Title string
	Body  string
}

func (editor *Editor) Save() EditorState {
	return EditorState{Title: editor.Title, Body: editor.Body}
}

func (editor *Editor) Restore(snapshot EditorState) {
	editor.Title = snapshot.Title
	editor.Body = snapshot.Body
}

func main() {
	document := &Editor{Title: "draft", Body: "hello"}
	checkpoint := document.Save()
	document.Body = "changed"
	document.Restore(checkpoint)
	fmt.Println(document.Body)
}

JavaScript example

class TextMemento {
  constructor(content) {
    this.content = content;
  }
}

class TextEditor {
  constructor() {
    this.text = '';
  }

  type(chunk) {
    this.text += chunk;
  }

  save() {
    return new TextMemento(this.text);
  }

  restore(memento) {
    this.text = memento.content;
  }
}

const editor = new TextEditor();
editor.type('go ');
const backup = editor.save();
editor.type('further');
editor.restore(backup);
console.log(editor.text);

Interview phrase

“Memento snapshots private state into an opaque object the caretaker holds; the editor can roll back without exposing internal fields to everyone.”

Map to LLD for undo stacks, draft autosave, or game save slots in LLD case studies.

Last updated on

Spotted something unclear or wrong on this page?

On this page