Java Reference
In-Depth Information
is a list of machine simulators. The
restore()
method for
FactoryModel
takes this list
as an argument and looks something like this:
public void restore(List memento)
{
machines = new ArrayList();
Iterator i = memento.iterator();
while (i.hasNext())
{
MachineImage mi = (MachineImage) i.next();
machines.add(mi.clone());
}
}
When the user clicks the Undo button, the visualization's
undo()
method pops the most
recent memento, discarding the state to undo. Then this method restores the simulation from
the memento at the top of the stack. Finally, this method disables the Undo button if the stack
contains only the initial memento.
CHALLENGE 19.3
Write the code for the visualization's
undo()
method.
In this example, a clone of a
MachineImage
object contains all the state information you
need to later set the object back to that state. Furthermore, a
FactoryModel
object needs
only a collection of clones of its machine images to store the state it needs to restore to in an
undo()
operation. When clones are available and they store the information you need to
create a memento, you can apply M
EMENTO
using clones. In other cases, you may need to
create a special class, such as
FactoryMemento
, to store the state of a factory model.
Persisting Mementos across Sessions
A
session
occurs when a user runs a program, conducts transactions in the program, and exits.
Suppose that your users want to be able to save a simulation in one session and restore it in
another session. This ability is a matter normally referred to as
persistent storage
. Persistent
storage fulfills the intent of the M
EMENTO
pattern and is a natural extension to the
undo
functionality you have already implemented.
Suppose that you subclass the
Visualization
class with a
Visual-ization2
class
1
that
has a menu bar with a File menu. This menu offers Save and Load commands that you link to
action methods:
1
The
Visualization2
class's name ends with a number but no underscore, to indicate that it is a revision but not a class
that will be refactored.