Easy patterns: Memento
This article is created in continuation to series of easy patterns description and describes behavioral pattern for saving current state of something with further interaction with previously saved value.
Creational patterns:
Structural patterns:
Behavioral patterns:
Memento (this article)
The main essence
The memento pattern is implemented with two objects: the originator and a caretaker. The originator is an object that has an internal state. The caretaker performs an operation on the originator, but can undo the change when it needed. The caretaker requests memento object from the originator. Then it applies the operation. The caretaker can roll back the originator to the initial state returning the memento object to the originator.
Example of use
In example above we create caretaker instance which can hold some values, added via setValue
method. At some point we are calling save
current caretaker state to originator instance. After that we continue to input values to it. After that we realized that we need to roll back to previously saved state with caretaker.restore
. Finally caretaker holds previously saved state.
Profit
It’s convenient to use this pattern to save state as milestones and move back and forward between them (undo/redo functionality).
Conclusion
If you found this article helpful, please hit the 👏 button and feel free to comment below!