Memento design pattern is used to capture the state of an object without violating encapsulation, so that if required then it can be
returned to its previous state.
Intent
Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored
to this state later.
The intent of memento design pattern is to capture the internal state of object without violating encapsulation, and restore to the same state if
required.
Problem
Need to save state of an object to restore it later. Saving it externally is difficult as it violates encapsulation.
There may be scenarios like undo, rollback, handling exceptions where object has to be restored to previous state.
Solution
Store the state of the object in another object and make it accessible from the object whose state is saved.
The object state will be saved in another object which will be created and accessed by same object so it will not violate the
encapsulation.
Where memento design pattern is applicable?
An Exception has to be handled in a way where an object has to be restored to its previous state.
The object state has to be stored somewhere to restore it later but should not be accessed by anyone, other than the
object whose state is saved.
Memento design pattern can be used in the scenarios of undo and rollback operations.
Memento Design Pattern UML Structure
Participant classes of memento design pattern
Originator class has the state to be captured. The method CreateMemnto() is used to instantiate the Memento
object which stores the state of the originator object; and Method SetMemnto() is used to get the previous state and
restore the same.
Memento class keeps the internal state of the originator object and can be accessed by originator only.
Caretaker class keeps the Memento object safely, this is nothing but a mechanism for undo or rollback.
How they work together?
The client uses caretaker which requests originator to have a memento; and if undo or rollback is required then pass
the memento to originator for restoring the object state. Originator accesses its previous state from memento and restores
the same.
So the object state is stored externally; and if required then it can be accessed to restore the same without
violating encapsulation. This may be expensive if object is large or many mementos have to be created. There may be
possibility to store state with incremental changes too.
Memento Design Pattern Example
Here is the memento design pattern example.
Virtual Machine is running and has some applications open. Save the state of machine, so that when you restart it should have same
environment as earlier.
Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books C In Depth,
Data Structures Through C In Depth. He has 18+ years experience in industry and worked on architecture and design of
multiple products. This article Memento Design Pattern is from his Design Patterns course.