Java Reference
In-Depth Information
Proxy
An address book grows tremendously over a period of time, since it stores all professional and social contacts. In
addition, users don't need the address book every time they use the PIM. They do need some kind of address book
placeholder to act as a starting point for them to use for graphical purposes, however. This example uses the
Proxy pattern to represent the address book.
AddressBook defines the interface for accessing the PIM address book. At the very least, it needs to have the
ability to add new contacts and to retrieve and store addresses.
Example A.191 AddressBook.java
1. import java.io.IOException;
2. import java.util.ArrayList;
3. public interface AddressBook {
4. public void add(Address address);
5. public ArrayList getAllAddresses();
6. public Address getAddress(String description);
7.
8. public void open();
9. public void save();
10. }
Retrieving the data for the address book might be very time-consuming, given the incredible popularity of the
users. Therefore, the proxy should delay creation of the real address book for as long as possible. The proxy,
represented by AddressBookProxy , has the responsibility for creating the address book— but only when
absolutely necessary.
Example A.192 AddressBookProxy.java
1. import java.io.File;
2. import java.io.IOException;
3. import java.util.ArrayList;
4. import java.util.Iterator;
5. public class AddressBookProxy implements AddressBook{
6. private File file;
7. private AddressBookImpl addressBook;
8. private ArrayList localAddresses = new ArrayList();
9.
10. public AddressBookProxy(String filename){
11. file = new File(filename);
12. }
13.
14. public void open(){
15. addressBook = new AddressBookImpl(file);
16. Iterator addressIterator = localAddresses.iterator();
17. while (addressIterator.hasNext()){
18. addressBook.add((Address)addressIterator.next());
19. }
20. }
21.
22. public void save(){
23. if (addressBook != null){
24. addressBook.save();
25. } else if (!localAddresses.isEmpty()){
26. open();
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;
 
Search WWH ::




Custom Search