Java Reference
In-Depth Information
6.
7. public void setPhoneNumber(String newNumber){
8. if (newNumber.length() == NUMBER_LENGTH){
9. super.setPhoneNumber(newNumber);
10. }
11. }
12. }
The
RunPattern
class provides an example of the
AbstractFactory
in use. It uses the
USAddressFactory
and
the
FrenchAddressFactory
to create two different sets of address/phone number combinations. It is significant
that once the factory objects have been loaded, we can deal with their products by using the
Address
and
PhoneNumber
interfaces. There are no method calls which depend on the distinction between a
USAddress
and a
FrenchAddress
.
Example A.10
RunPattern.java
1. public class RunPattern{
2. public static void main(String [] arguments){
3. System.out.println("Example for the AbstractFactory pattern");
4. System.out.println();
5. System.out.println(" (take a look in the RunPattern code. Notice that you can");
6. System.out.println(" use the Address and PhoneNumber classes when writing");
7. System.out.println(" almost all of the code. This allows you to write a very");
8. System.out.println(" generic framework, and plug in Concrete Factories");
9. System.out.println(" and Products to specialize the behavior of your code)");
10. System.out.println();
11.
12. System.out.println("Creating U.S. Address and Phone Number:");
13. AddressFactory usAddressFactory = new USAddressFactory();
14. Address usAddress = usAddressFactory.createAddress();
15. PhoneNumber usPhone = usAddressFactory.createPhoneNumber();
16.
17. usAddress.setStreet("142 Lois Lane");
18. usAddress.setCity("Metropolis");
19. usAddress.setRegion("WY");
20. usAddress.setPostalCode("54321");
21. usPhone.setPhoneNumber("7039214722");
22.
23. System.out.println("U.S. address:");
24. System.out.println(usAddress.getFullAddress());
25. System.out.println("U.S. phone number:");
26. System.out.println(usPhone.getPhoneNumber());
27. System.out.println();
28. System.out.println();
29.
30. System.out.println("Creating French Address and Phone Number:");
31. AddressFactory frenchAddressFactory = new FrenchAddressFactory();
32. Address frenchAddress = frenchAddressFactory.createAddress();
33. PhoneNumber frenchPhone = frenchAddressFactory.createPhoneNumber();
34.
35. frenchAddress.setStreet("21 Rue Victor Hugo");
36. frenchAddress.setCity("Courbevoie");
37. frenchAddress.setPostalCode("40792");
38. frenchPhone.setPhoneNumber("011324290");
39.
40. System.out.println("French address:");
41. System.out.println(frenchAddress.getFullAddress());
42. System.out.println("French phone number:");
43. System.out.println(frenchPhone.getPhoneNumber());
44. }
45. }