Design Patterns Java™ Workbook

(Michael S) #1

Chapter 19. Memento...................................................................................................................................


Chapter 19. Memento


Sometimes, you want to create an object that existed previously. This occurs when you want
to let a user undo operations, revert to an earlier version of work, or resume work that he or
she previously suspended. The intent of the MEMENTO pattern is to provide storage and
restoration of an object's state.


Memento Durability....................................................................................................................................


A memento is a tiny repository that saves an object's state. You can create a memento by
using another object, a string, or a file. The anticipated duration between the storage and
the reconstruction of an object has an effect on the strategy that you can use in designing
a memento. The time that elapses can be moments, hours, days, or years.


CHALLENGE 19.1


Write down two reasons that might drive you to saving a memento in a file rather
than as an object.

Applying Memento.....................................................................................................................................


In the preceding chapter, you used the PROTOTYPE pattern to design a simulation that let users
speculatively create new machine simulators from existing ones. Your users like the
simulation, but they sometimes make changes that they wish they could undo.


You might consider using the javax.swing.undo package to support an undo operation.
However, the undo package focuses its support on operations for textual Swing components.
In this application, it is simpler to apply the MEMENTO pattern to save and to restore the state
of the simulation at key points.



  • Each time the user adds or moves a machine in the visualization, your code will create
    a memento of the simulated factory and add it to a stack.

  • Each time the user clicks the Undo button, your code will pop the most recent
    memento and then restore the simulation to the state stored at the top of the stack.


When your visualization starts up, you will stack an initial, empty memento and never pop it,
to ensure that the top of the stack is always a valid memento. Any time the stack contains just
one memento, you disable the Undo button. Figure 19.1 shows the visualization after the user
has added and dragged several machines into place.

Free download pdf