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
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.
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.
- The Client makes a change to the Originator.
- The Originator creates a new Memento which represents its current state.
- The Client stores the Memento into the Caretaker in order to change between different Originatorstates.
- After some time, the Client sends a request to the Caretaker for a previous state of the Originator.
- The Client uses the Memento sent by the Caretaker to restore the state of the Originator .
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).