Java Reference
In-Depth Information
Adapter (page 142) - An Adapter provides a front interface to a specific object, as does the Proxy pattern.
However, the Proxy provides the same interface as the object, and the Adapter provides a different interface.
HOPP (page 189) - The HOPP pattern can use the Proxy pattern for the communication between the two
distributed halves of the HOPP.
Business Delegate [CJ2EEP] - The Business Delegate pattern can be used as a Proxy. The Business Delegate
can be a local representative of the Business tier.
Example
Note:
For a full working example of this code example, with additional supporting classes and/or a RunPattern class,
see “ Proxy ” on page 492 of the “ Full Code Examples ” appendix.
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 3.32 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 3.33 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();
Search WWH ::




Custom Search