Java Reference
In-Depth Information
45. }
46. }
47. }
48. if (addressBook == null){
49. open();
50. }
51. return addressBook.getAddress(description);
52. }
53.
54. public void add(Address address){
55. if (addressBook != null){
56. addressBook.add(address);
57. } else if (!localAddresses.contains(address)){
58. localAddresses.add(address);
59. }
60. }
61. }
Note that the AddressBookProxy has its own ArrayList for addresses. If the user adds an address by calling the
add method, the proxy can use its internal address book without using the real address book.
The AddressBookImpl class represents the real address book for a user. It is associated with a file that stores an
ArrayList with all the user's addresses. AddressBookProxy would create an AddressBookImpl object only
when it is needed—when a user called the method getAllAddresses , for example.
Example A.193 AddressBookImpl.java
1. import java.io.File;
2. import java.io.IOException;
3. import java.util.ArrayList;
4. import java.util.Iterator;
5. public class AddressBookImpl implements AddressBook {
6. private File file;
7. private ArrayList addresses = new ArrayList();
8.
9. public AddressBookImpl(File newFile) {
10. file = newFile;
11. open();
12. }
13.
14. public ArrayList getAllAddresses(){ return addresses; }
15.
16. public Address getAddress(String description){
17. Iterator addressIterator = addresses.iterator();
18. while (addressIterator.hasNext()){
19. AddressImpl address = (AddressImpl)addressIterator.next();
20. if (address.getDescription().equalsIgnoreCase(description)){
21. return address;
22. }
23. }
24. return null;
25. }
26.
27. public void add(Address address) {
28. if (!addresses.contains(address)){
29. addresses.add(address);
30. }
31. }
32.
33. public void open(){
34. addresses = (ArrayList)FileLoader.loadData(file);
35. }
36.
37. public void save(){
38. FileLoader.storeData(file, addresses);
39. }
40. }
AddressBookImpl delegates the task of loading and saving files to a worker class called FileLoader . This class
has methods to read and write Serializable objects to a file.
Example A.194 FileLoader.java
1. import java.io.File;
2. import java.io.FileInputStream;
3. import java.io.FileOutputStream;
Search WWH ::




Custom Search