Design Patterns Java™ Workbook

(Michael S) #1
Appendix B. Solutions

Memento (Chapter 19)..............................................................................................................................


SOLUTION 19.1....................................................................................................................................


Storing a memento as an object assumes that the application will still be running when
the user wants to restore the original object. Reasons that will force you to save a memento to
persistent storage follow.



  • The ability to restore an object's state has to survive a system crash.

  • You anticipate that the user will exit the system and will want to resume work later.

  • You need to reconstruct an object on another computer.


SOLUTION 19.2....................................................................................................................................


Here is an implementation of createMemento() for FactorySimulator:


public List createMemento()
{
List list = new ArrayList();
Iterator i = machines.iterator();
while (i.hasNext())
{
MachineImage mi = (MachineImage) i.next();
list.add(mi.clone());
}
return list;
}


When you write a createMemento() method, you should convince yourself or your
colleagues that the method returns all the information necessary to reconstruct the receiving
object. In this example, a machine simulator can reconstruct itself from a clone, and a factory
simulator can reconstruct itself from a list of machine simulator clones.


SOLUTION 19.3....................................................................................................................................


Here is a solution that performs the described behavior of the Undo button:


protected void undo()
{
if (mementos.size() > 1)
{
mementos.pop();
List s = (List) mementos.peek();
factory().restore(s);
undoButton().setEnabled(mementos.size() > 1);
vizPanel().repaint();
}
}


Note that the factory(),undoButton(), and vizPanel() method names match
the ones given in Figure 19.2. If the other methods in the GUI application work correctly, this

Free download pdf