Published on

[Behavioral] Memento

Real world example

Take the example of calculator (i.e. originator), where whenever you perform some calculation the last calculation is saved in memory (i.e. memento) so that you can get back to it and maybe get it restored using some action buttons (i.e. caretaker).

In plain words

Memento pattern is about capturing and storing the current state of an object in a manner that it can be restored later on in a smooth manner.

Wikipedia says

The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).

Programmatic Example

Lets take an example of text editor which keeps saving the state from time to time and that you can restore if you want.

First of all we have our memento object that will be able to hold the editor state

class EditorMemento {
    protected content

    constructor(content: string) {
        this.content = content
    }

    getContent() {
        return this.content
    }
}

Then we have our editor i.e. originator that is going to use memento object

export class Editor {
    protected content: string = '';

    type(words: string) {
        this.content += words
    }

    getContent() {
        return this.content;
    }

    save() {
        return new EditorMemento(this.content)
    }

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

And then it can be used as

test('test memento design pattern', () => {
    const editor = new Editor();

    editor.type('first')
    expect(editor.getContent()).toEqual('first')
    editor.type('second')
    expect(editor.getContent()).toEqual('firstsecond')

    const saved = editor.save()

    editor.type('third')
    expect(editor.getContent()).toEqual('firstsecondthird')

    editor.restore(saved)
    expect(editor.getContent()).toEqual('firstsecond')
})

References