Design Pattern | Memento Pattern

What Is the Memento Pattern?

  • Memento means souvenir, keepsake, or reminder.
  • To implement Undo in an object-oriented program, you must save the information held by an instance.
  • To restore an instance, you need access to the internal information of that instance. However, if access is allowed carelessly, code becomes dependent on the internal structure of the class. This is called breaking encapsulation.
  • The Memento pattern introduces a role that represents the state of an instance and saves/restores state, or previous instances, without breaking encapsulation.
  • In GoF design patterns, it is classified as a behavioral design pattern.

Memento Pattern Example Program

The example changes money and possessions(fruit) according to the number rolled on a die.
Depending on the situation, it saves and restores state.

Class Diagram
Memento Pattern Class Diagram

The example has a Memento class that represents the state of the game, a Gamer class that changes state, and a Main class that keeps a snapshot when conditions are good and restores it when conditions are bad.

Advantages

Memento allows state to be saved without exposing the internal structure of the object. This is useful for Undo, rollback, checkpoints, and recovery features while preserving encapsulation.