Also known as

Memento

Intent

Without violating encapsulation, capture and externalize an object's internal state so that the object can be returned to this state later.

Structure of design pattern

Classic implementation

Memento pattern structure

Improved encapsulation

There is alternative Memento implementation that has even stricter control over the originator data.

Secure Memento pattern

Pseudocode

// Originator class should have a special method, which captures originator's
// state inside a new memento object.
class Editor is
    private field text: string
    private field cursorX, cursorY, selectionWidth

    method setText(text) is
        this.text = text

    method setCursor(x, y) is
        this.cursorX = cursorX
        this.cursorY = cursorY

    method selectionWidth(width) is
        this.selectionWidth = width

    method saveState():EditorState is
        // Memento is immutable object; that's why originator passes its state
        // to memento's constructor parameters.
        return new EditorState(this, text, cursorX, cursorY, selectionWidth)

// Memento stores past state of the editor.
class EditorState is
    private field editor: Editor
    private field text: string
    private field cursorX, cursorY, selectionWidth

    constructor EditorState(editor, text, cursorX, cursorY, selectionWidth) is
        this.editor = editor
        this.text = text
        this.cursorX = cursorX
        this.cursorY = cursorY
        this.selectionWidth = selectionWidth

    // At some point, old editor state can be restored using a memento object.
    method restore() is
        editor.setText(text)
        editor.setCursor(cursorX, cursorY)
        editor.selectionWidth(selectionWidth)

// Command object could act as a client of this pattern. In such case, command
// gets a memento just before it changes the originator's state. When undo is
// requested, it restores originator's state with a memento.
class Command is
    field backup: EditorState

    method backup() is
        backup = editor.saveState()

    method undo() is
        if (backup != null)
            backup.restore()
    // ...

Implementations in Different Programming Languages

Java