Memento Design Pattern In Java

Today, I would like to discuss another behavioral design pattern called the Memento Design Pattern which is used to restore the state of an object to a previous state.

Memento Design Pattern

  • The Memento Design Pattern is one of the twenty-three well-known GoF design patterns that provide the ability to restore an object to its previous state.
  • The Memento Design Pattern is implemented with the help of three objects: the originator, a caretaker, and a memento
    • Originator — The object whose internal state we like to store. The Originator object creates a memento object to store its internal state. So, the Originator object knows how to save and restore itself. The object which gets and sets the values of Memento objects.
    • Caretaker — The object which knows why and when the Originator needs to save and restore itself. The object operates on the Originator while having the possibility to rollback. It maintains the history of the Memento objects created. The caretaker takes a snapshot of Originator before operating.
    • Memento — The POJO object that contains basic state storage and retrieval capabilities.  The Memento object is immutable in general. The object holds the internal state of the Originator and allows it to restore it.
  • The classic example of the Memento Pattern is a pseudorandom number generator or finite state machine.
  • Git stashing is another example of the Momento Design Pattern.
  • The internal state of the Originator object should be saved externally so that the object can be restored to this state later. Also, the object's encapsulation must not be violated.
  •  The caretaker requests a Momento from Originator before operating. And use that Momento to restore the Originator to its previous state if needed.
  • We can make Memento Design Pattern implementation more generic by using Serialization; that will eliminate the requirement of every class having its own Momento class.
  • The Memento Design Pattern can also be used with the Command Design Pattern for achieving undo of the commands.

mementodesign

To understand the Memento Design Pattern let's take the example of the Employee class storing and retrieving its state using EmployeeMemento class.