The memento pattern
The memento pattern is useful if you need to preserve multiple states of your program or models, which you want to be able to go back or forward to, such as a browsing history or an undo manager.
In this section, we'll implement the memento pattern with a simple example that showcases the different objects required for this pattern.
Components of the memento pattern
The memento pattern requires the implementation of three distinct entities:
Memento
: a representation of the internal state ofOriginator
, which should be immutableOriginator
: the original object that can produce and consume theMemento
, in order to save and restore its own stateCareTaker
: an external object that stores and restores aMemento
to anOriginator
Note
Memento
, in other languages, may be implemented as an opaque box so the state can't be mutated. In Swift, we can leverage structs, their immutability, and the fact they are passed by value and not reference. It is critical that different Memento
objects...