Java Reference
In-Depth Information
Command (page 51) - Command can use Mementos to keep track of state for undoable actions.
State (page 104) - Most States use Memento.
Example
Note:
For a full working example of this code example, with additional supporting classes and/or a
RunPattern
class,
Almost all parts of the Personal Information Manager keep some kind of state. These states can be saved by
applying the Memento pattern, as this example with an address book will demonstrate. The
AddressBook
class
represents a collection of addresses, a natural candidate for keeping a record of state.
Example 2.31
AddressBook.java
1. import java.util.ArrayList;
2. public class AddressBook{
3. private ArrayList contacts = new ArrayList();
4.
5. public Object getMemento(){
6. return new AddressBookMemento(contacts);
7. }
8. public void setMemento(Object object){
9. if (object instanceof AddressBookMemento){
10. AddressBookMemento memento = (AddressBookMemento)object;
11. contacts = memento.state;
12. }
13. }
14.
15. private class AddressBookMemento{
16. private ArrayList state;
17.
18. private AddressBookMemento(ArrayList contacts){
19. this.state = contacts;
20. }
21. }
22.
23. public AddressBook(){ }
24. public AddressBook(ArrayList newContacts){
25. contacts = newContacts;
26. }
27.
28. public void addContact(Contact contact){
29. if (!contacts.contains(contact)){
30. contacts.add(contact);
31. }
32. }
33. public void removeContact(Contact contact){
34. contacts.remove(contact);
35. }
36. public void removeAllContacts(){
37. contacts = new ArrayList();
38. }
39. public ArrayList getContacts(){
40. return contacts;
41. }
42. public String toString(){
43. return contacts.toString();
44. }
45. }
The inner class of
AddressBook
,
AddressBookMemento
, is used to save the state of an
AddressBook
, which in
this case is represented by the internal
ArrayList
of
Address
objects. The memento object can be accessed by
using the
AddressBook
methods
getMemento
and
setMemento
. Note that
AddressBookMemento
is a private inner
class and that it has only a private constructor. This ensures that, even if the memento object is saved somewhere
outside of an
AddressBook
object, no other object will be able to use the object or modify its state. This is
consistent with the role of the Memento pattern: producing an object to maintain a snapshot of state that cannot be
modified by other objects in a system.