Java Reference
In-Depth Information
Creational Pattern Code Examples
Abstract Factory
The following code samples show how international addresses and phone numbers can be supported in the
Personal Information Manager with the Abstract Factory pattern. The
AddressFactory
interface represents the
factory itself:
Example A.1
AddressFactory.java
1. public interface AddressFactory{
2. public Address createAddress();
3. public PhoneNumber createPhoneNumber();
4. }
Note that the
AddressFactory
defines two factory methods,
createAddress
and
createPhoneNumber
. The
methods produce the abstract products
Address
and
PhoneNumber
, which define methods that these products
support.
Example A.2
Address.java
1. public abstract class Address{
2. private String street;
3. private String city;
4. private String region;
5. private String postalCode;
6.
7. public static final String EOL_STRING =
8. System.getProperty("line.separator");
9. public static final String SPACE = " ";
10.
11. public String getStreet(){ return street; }
12. public String getCity(){ return city; }
13. public String getPostalCode(){ return postalCode; }
14. public String getRegion(){ return region; }
15. public abstract String getCountry();
16.
17. public String getFullAddress(){
18. return street + EOL_STRING +
19. city + SPACE + postalCode + EOL_STRING;
20. }
21.
22. public void setStreet(String newStreet){ street = newStreet; }
23. public void setCity(String newCity){ city = newCity; }
24. public void setRegion(String newRegion){ region = newRegion; }
25. public void setPostalCode(String newPostalCode){ postalCode = newPostalCode; }
26. }
Example A.3
PhoneNumber.java
1. public abstract class PhoneNumber{
2. private String phoneNumber;
3. public abstract String getCountryCode();
4.
5. public String getPhoneNumber(){ return phoneNumber; }
6.
7. public void setPhoneNumber(String newNumber){
8. try{
9. Long.parseLong(newNumber);
10. phoneNumber = newNumber;
11. }
12. catch (NumberFormatException exc){
13. }
14. }
15. }
Address
and
PhoneNumber
are abstract classes in this example, but could easily be defined as interfaces if you
did not need to define code to be used for all concrete products.
To provide concrete functionality for the system, you need to create Concrete Factory and Concrete Product
classes. In this case, you define a class that implements
AddressFactory
, and subclass the
Address
and
PhoneNumber
classes. The three following classes show how to do this for U.S. address information.
Example A.4
USAddressFactory.java