Java Reference
In-Depth Information
Memento
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 A.83
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.
Support classes used in this example provide business objects for the contacts stored in the
AddressBook
, and
their associated addresses. The
Address
and
Contact
interfaces define the behavior expected of these business
objects, while the
AddressImpl
and
ContactImpl
classes implement the required behavior.
Example A.84
Address.java
1. import java.io.Serializable;
2. public interface Address extends Serializable{
3. public static final String EOL_STRING = System.getProperty("line.separator");
4. public static final String SPACE = " ";
5. public static final String COMMA = ",";