The memento pattern

Tharaka Dissanayake
2 min readJul 19, 2022

The Memento Design Pattern is a behavioural pattern that provides the ability to restore an object to its previous state. There are three objects in the memento pattern. They are the originator, a caretaker, and a memento.

The originator creates, saves and restores objects the object. A memento object to store its internal state. The caretaker takes a snapshot of the originator before operating. Memento contains primary state storage and retrieval capabilities.

This memento pattern will be used to produce snapshots of the object’s state without violating its encapsulation. But it consumes more RAM if clients create mementoes too often.

In the Gang Of Four book, it is shown as follows.

Example:

We can design a text editor using a memento pattern. When we need to undo the editor state, we need to keep each state.

We need to create a history class to store the editor's state.

Editor class
Editor state class
History class
Main class

References: https://www.youtube.com/watch?v=Pwm-jrG2ZVA&ab_channel=KrishDinesh

--

--