DEV Community

Coder
Coder

Posted on • Originally published at itscoderslife.wordpress.com on

Memento Design Pattern [Behavioral]

What? – The memento lets us take a snapshot of an object’s important state.

When implementing this pattern, it is important to keep the safe state external to the object. The object’s internal state is not exposed, thus we don’t break encapsulation. The captured state is kept in a memento object. Later we can restore the object with this saved state.

There are three distinct roles in this pattern:

DP-Memento.jpg

  1. The originator, this is the object that we want to restore to a given state. It has two methods:
    1. The createMemento returns a memento instance, which holds the information needed to reset the originator to that state.
    2. The restore method, which takes the memento parameter that includes the previously saved state. The restore method resets the originator to this state.
  2. The memento is quite simple, it has a state. This can be a built-in or a custom type that can hold the originator’s state; it doesn’t contain any further logic. The caretaker provides the save and restore functionality. It asks the originator to save its state or to return to a previously saved state.
  3. The caretaker keeps track of all the previously created mementos.

The memento captures the important state of an object without exposing its internal data. The saved state can be used to reset the object to a previous state if needed. The memento can be used to implement undo and redo operations.

Example: Game states are saved when a player hits a checkpoint. The state of the game can include anything from a number of enemies or coins collected etc. When the player quits and starts the game later the same state at last checkpoint is restored.

Another typical example where Memento can be used in the Undo mechanism used.

The memento pattern captures the important state of an object into a memento. This memento can be used to restore the object at a later date. The pattern is implemented correctly if the originator’s internal state is not exposed to the client.

Disadvantages: Saving and restoring the state of a complex object may be time-consuming. You should carefully consider performance implications when implementing the memento pattern. Another frequent problem is exposing the originator’s internal details, thus breaking encapsulation. The client should rely solely on the caretaker to save and restore the state of the originator.

Top comments (0)