Java Reference
In-Depth Information
39. }
40. }
RunPattern demonstrates how the proxy could work in practice. First, it creates an AddressBookProxy and adds
several new Address objects to the Proxy. These new addresses will initially be stored locally. It is only when the
example calls the method getAllAddresses that the Proxy will create an AddressBookImpl object and retrieve
addresses stored in the file.
Example A.198 RunPattern.java
1. import java.io.File;
2. import java.io.IOException;
3. import java.util.ArrayList;
4. public class RunPattern{
5. public static void main(String [] arguments){
6. System.out.println("Example for the Proxy pattern");
7. System.out.println();
8. System.out.println("This code will demonstrate the use of a Proxy to");
9. System.out.println(" provide functionality in place of its underlying");
10. System.out.println(" class.");
11. System.out.println();
12.
13. System.out.println(" Initially, an AddressBookProxy object will provide");
14. System.out.println(" address book support without requiring that the");
15. System.out.println(" AddressBookImpl be created. This could potentially");
16. System.out.println(" make the application run much faster, since the");
17. System.out.println(" AddressBookImpl would need to read in all addresses");
18. System.out.println(" from a file when it is first created.");
19. System.out.println();
20.
21. if (!(new File("data.ser").exists())){
22. DataCreator.serialize("data.ser");
23. }
24. System.out.println("Creating the AddressBookProxy");
25. AddressBookProxy proxy = new AddressBookProxy("data.ser");
26. System.out.println("Adding entries to the AddressBookProxy");
27. System.out.println("(this operation can be done by the Proxy, without");
28. System.out.println(" creating an AddressBookImpl object)");
29. proxy.add(new AddressImpl("Sun Education [CO]", "500 El Dorado Blvd.", "Broomfield", "CO",
"80020"));
30. proxy.add(new AddressImpl("Apple Inc.", "1 Infinite Loop", "Redwood City", "CA", "93741"));
31. System.out.println("Addresses created. Retrieving an address");
32. System.out.println("(since the address is stored by the Proxy, there is");
33. System.out.println(" still no need to create an AddressBookImpl object)");
34. System.out.println();
35. System.out.println(proxy.getAddress("Sun Education [CO]").getAddress());
36. System.out.println();
37.
38. System.out.println("So far, all operations have been handled by the Proxy,");
39. System.out.println(" without any involvement from the AddressBookImpl.");
40. System.out.println(" Now, a call to the method getAllAddresses will");
41. System.out.println(" force instantiation of AddressBookImpl, and will");
42. System.out.println(" retrieve ALL addresses that are stored.");
43. System.out.println();
44.
45. ArrayList addresses = proxy.getAllAddresses();
46. System.out.println("Addresses retrieved. Addresses currently stored:");
47. System.out.println(addresses);
48. }
49. }
Search WWH ::




Custom Search