Easy patterns: Memento

Ruslan Malogulko
ITNEXT
Published in
2 min readJun 23, 2018

--

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:

Simple Factory

Factory method

Builder

Singleton

Abstract factory

Prototype

Structural patterns:

Adapter

Decorator

Bridge

Composite

Facade

Flyweight

Proxy

Behavioral patterns:

Visitor

Mediator

Observer

Memento (this article)

Iterator

Chain Of Responsibility

Strategy

State

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!

--

--