The Memento design pattern provides a solution:
Define
Originator and Memento
objects
so that
an originator saves/restores its internal state to/from a memento.
Describing the Memento design in more detail is the theme
of the following sections.
See Applicability section for all problems Memento can solve.
Originator
and
Memento
objects:
Originator defines an operation for
saving
its internal state
to a memento
(createMemento(): return new Memento(state))
and for restoring
to a previous state
from a memento
(restore(memento): state = memento.getState()).
Memento defines
the required data structures to store
an originator's internal state,
and it is protected against access by
objects other than the originator.