Memento

Behavioral pattern

This design pattern allows us to record the state of an object on a specific moment in order to return it to that state at any given time. Memento is useful when we have many objects changing over time and, for some reason, we need to restore them to a previous state.

Memento design pattern structure
Memento design pattern structure

The components included in the pattern are:

  • Client: This component affects the Originator and records a new state into the Caretaker. In other words, it's the one making changes to the object and recording its state.
  • Originator: It is the component whose state is changing.
  • Memento: It is the component storing the Originator's state on a specific moment.
  • Caretaker: This is the component registering all the changes happening in the Originator. It allows us to travel to any previous state of the Originator.
Memento design pattern sequence diagram
Memento design pattern sequence diagram
  1. The Client makes a change to the Originator.
  2. The Originator creates a new Memento which represents its current state.
  3. The Client stores the Memento into the Caretaker in order to change between different Originatorstates.
  4. After some time, the Client sends a request to the Caretaker for a previous state of the Originator.
  5. The Client uses the Memento sent by the Caretaker to restore the state of the Originator .

Real-world example

By implementing the Memento design pattern, we are going to develop a simple but effective application for receiving information about an employee. Once the information is stored, the application will allow us to go back or forward between different versions of this information that were stored by the Memento pattern, as if we were using an undo (Ctrl + Z) and redo features (Ctrl + Y).

Discover how the Memento pattern can help us solve this problem
Discover how the Memento pattern can help us solve this problem

About this book

Introduction to design patterns

Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:

See book
All rights reserved ©
Reactive programming
LinkedinYoutubeTwitterFacebook

© 2021, Copyright - Oscar Blancarte. All rights reserved.