Behavioral – Memento Design Pattern
August 14, 2020 2 min read

Memento pattern is a behavioral design pattern that used to restore state of an object to a previous state. When an application is progressing, you may want to save checkpoints in your application and restore back to those checkpoints later. For that we use memento pattern.
There are 3 design components called Originator, Caretaker and Memento for the memento pattern. Let’s discuss about those components using an example.
I am going to create a memento for an article. Let’s see how to create it.

This is the “Article” class which has three attributes id, title, and content. Let’s see what is the return type given to the method “createMemento()” from the next step.

“ArticleMemento” is the class that we used as “Memento” for “Article” objects. This is an encapsulated class. Let’s discuss about the “Memento” later.
You can see two methods called “createMemento()” and “restore(memento)” in the class “Article”. Those methods are provided by the component called “Originator”. It is the object that knows how to create and save it’s state for future.
“Caretaker” class refers to the “Originator” class for saving (createMemento()) and restoring (restore(memento)) originator’s internal state. “Caretaker” performs an operation on the “Originator” while having the possibility to rollback. It keeps track of multiple mementos. Main method is acting as the “Caretaker”. Let’s see the main method of the above example.

“Memento” is the component or the lock box that is written and read by the Originator, and shepherded by the Caretaker. In principle, a memento must be in immutable object so that no one can change it’s state once created.
Let’s see the output of the above example.

You can visit the below given articles to learn about creational design patterns and Structural Design Patterns.
Thank you.
Creational Design Patterns
Abstract Factory Design Pattern
Structural Design Patterns


