Undo Changes With Memento Pattern

Nisal Jayathilaka
2 min readDec 27, 2021

Memento is a behavioural design pattern that lets you capture the object’s internal state without exposing its internal structure, o that the object can be returned to this state later.

The memento design pattern has three states Memento Originator and Caretaker. Originator is the one we need to maintain the state (It acts like a memory generator or memento generator). The caretaker is the one who keeps track of the originator and memento itself (It can save all these mementoes Sates inside the caretaker. Caretaker has no way to change the memento state).

Follow the steps for creating Memento

  • Create a Memento class with the required state you want to persist.
  • Create an Originator class which on save, which saves the state to a memento class.
  • Make a caretaker class that has a list of memento states and a cursor pointing to the last know state.
  • Provide methods to go forward and backwards in the state timeline with undo and redo methods for the caretaker.
  • Create an Originator and a Caretaker. Create some states and do undo and redo on demand based on the requirement.

Sample:-

--

--