Java Reference
In-Depth Information
protected void load()
{
int dialogStatus = fc().showOpenDialog(null);
if (dialogStatus == JFileChooser.APPROVE_OPTION)
{
File f = fc.getSelectedFile();
try
{
ObjectInputStream in =
new ObjectInputStream(
new FileInputStream(f));
List m = (List) in.readObject();
in.close();
mementos.removeAllElements();
mementos.push(m);
factory().restore(m);
undoButton().setEnabled(false);
vizPanel().repaint();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
For another complete example of applying serialization, see Java™ Examples in a Nutshell
(Flanagan 1997).
Using Strings as Mementos
Object serialization provides a simple means for a memento to persist across multiple sessions
that occur, say, on a given day. If, on the other hand, your user wants to revive a simulation
after a six-month sabbatical, he or she may find that various classes in the simulation package
have evolved to new versions. The java.io package provides some support for deserializing
an object when its class has changed since the serialization was written, but proper handling
of object serialization across class versions is, in practice, problematic. To avoid this problem,
you can "serialize" your object to text.
One way to provide persistent storage of an object is to write out a textual description of it.
You can save an object's data as an XML file or in a proprietary language of your own design.
When you read in such a file, it is comparatively easy to handle missing data or changes in
class design that can occur when a class version changes while the data is in storage.
CHALLENGE 19.5
Write down at least one disadvantage of storing an object as text.
Design Patterns (Gamma et al. 1995) states the intent of the M EMENTO pattern as, "Without
violating encapsulation, capture and externalize an object's internal state so that the object can
be restored to this state later" (p. 283). You might argue that this intent addresses online
Search WWH ::




Custom Search