Java Reference
In-Depth Information
27. addressBook.save();
28. }
29. }
30.
31. public ArrayList getAllAddresses(){
32. if (addressBook == null) {
33. open();
34. }
35. return addressBook.getAllAddresses();
36. }
37.
38. public Address getAddress(String description){
39. if (!localAddresses.isEmpty()){
40. Iterator addressIterator = localAddresses.iterator();
41. while (addressIterator.hasNext()){
42. AddressImpl address = (AddressImpl)addressIterator.next();
43. if (address.getDescription().equalsIgnoreCase(description)){
44. return address;
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 3.34 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. }
Search WWH ::




Custom Search