Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

Abstract Factory

Also known as Kit, Toolkit

Pattern Properties

Type: Creational, Object
Level: Component

Purpose

To provide a contract for creating families of related or dependent objects without having to specify their concrete classes.

Introduction

Suppose you plan to manage address and telephone information as part of a personal information manager (PIM) application. The PIM will act as a combination address book, personal planner, and appointment and contact manager, and will use the address and phone number data extensively.

You can initially produce classes to represent your address and telephone number data. Code these classes so that they store the relevant information and enforce business rules about their format. For example, all phone numbers in North America are limited to ten digits and the postal code must be in a particular format.

Shortly after coding your classes, you realize that you have to manage address and phone information for another country, such as the Netherlands. The Netherlands has different rules governing what constitutes a valid phone number and address, so you modify your logic in the Address and PhoneNumber classes to take the new country into account.

Now, as your personal network expands, you need to manage information from another foreign country... and another... and another. With each additional set of business rules, the base Address and PhoneNumber classes become even more bloated with code and even more difficult to manage. What's more, this code is brittle—with every new country added, you need to modify and recompile the classes to manage contact information.

It's better to flexibly add these paired classes to the system; to take the general rules that apply to address and phone number data, and allow any number of possible foreign variations to be "loaded" into a system.

The Abstract Factory solves this problem. Using this pattern, you define an AddressFactory—a generic framework for producing objects that follow the general pattern for an Address and PhoneNumber. At runtime, this factory is paired with any number of concrete factories for different countries, and each country has its own version of Address and PhoneNumber classes.

Instead of going through the nightmare of adding functional logic to the classes, extend the Address to a DutchAddress and the PhoneNumber to a DutchPhoneNumber. Instances of both classes are created by a DutchAddressFactory. This gives greater freedom to extend your code without having to make major structural modifications in the rest of the system.

Applicability

Use the Abstract Factory pattern when:

  • The client should be independent of how the products are created.

  • The application should be configured with one of multiple families of products.

  • Objects need to be created as a set, in order to be compatible.

  • You want to provide a collection of classes and you want to reveal just their contracts and their relationships, not their implementations.

Description

Sometimes an application needs to use a variety of different resources or operating environments. Some common examples include:

  • Windowing (an application's GUI)
  • A file system
  • Communication with other applications or systems

In this sort of application you want to make the application flexible enough to use a variety of these resources without having to recode the application each time a new resource is introduced.

An effective way to solve this problem is to define a generic resource creator, the Abstract Factory. The factory has one or more create methods, which can be called to produce generic resources or abstract products.

Java ("Java technology") runs on many platforms, each with many different implementations of a file system or windowing. The solution Java has taken is to abstract the concepts of files and windowing and not show the concrete implementation. You can develop the application using the generic capabilities of the resources as though they represented real functionality.

During runtime, ConcreteFactories and ConcreteProducts are created and used by the application. The concrete classes conform to the contract defined by the AbstractFactory and AbstractProducts, so the concrete classes can be directly used, without being recoded or recompiled.

Implementation

The Abstract Factory class diagram is shown in Figure 1.1.

Figure 1.1 Abstract Factory class diagram

You typically use the following to implement the Abstract Factory pattern:

  • AbstractFactory – An abstract class or interface that defines the create methods for abstract products.

  • AbstractProduct – An abstract class or interface describing the general behavior of the resource that will be used by the application.

  • ConcreteFactory – A class derived from the abstract factory. It implements create methods for one or more concrete products.

  • ConcreteProduct – A class derived from the abstract product, providing an implementation for a specific resource or operating environment.

Benefits and Drawbacks

An Abstract Factory helps to increase the overall flexibility of an application. This flexibility manifests itself both during design time and runtime. During design, you do not have to predict all future uses for an application. Instead, you create the generic framework and then develop implementations independently from the rest of the application. At runtime, the application can easily integrate new features and resources.

A further benefit of this pattern is that it can simplify testing the rest of the application. Implementing a TestConcreteFactory and TestConcreteProduct is simple; it can simulate the expected resource behavior.

To realize the benefits of this pattern, carefully consider how to define a suitably generic interface for the abstract product. If the abstract product is improperly defined, producing some of the desired concrete products can be difficult or impossible.

Pattern Variants

As mentioned earlier, you can define the AbstractFactory and AbstractProduct as an interface or an abstract class, depending on the needs of the application and your preference.

Depending on how the factory is to be used, some variations of this pattern allow multiple ConcreteFactory objects to be produced, resulting in an application that can simultaneously use multiple families of ConcreteProducts.

Related Patterns

Related patterns include the following:

  • Factory Method (page 21) – Used to implement the Abstract Factory.

  • Singleton (page 34) – Often used in the Concrete Factory.

  • Data Access Object [CJ2EEP] – The Data Access Object pattern can use the Abstract Factory pattern to add flexibility in creating Database-specific factories.

NOTE

"[CJ2EEP]" refers to J2EE patterns, listed in the bibliography (see page 559).

Example

The following code shows 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 1.1 AddressFactory.java 0

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 1.2 Address.java 0

 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 1.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 1.4 USAddressFactory.java 0

1. public class USAddressFactory implements AddressFactory{
2.   public Address createAddress(){
3.     return new USAddress();
4.   }
5.   
6.   public PhoneNumber createPhoneNumber(){
7.     return new USPhoneNumber();
8.   }
9. }

Example 1.5 USAddress.java 0

 1. public class USAddress extends Address{
 2.   private static final String COUNTRY = "UNITED STATES";
 3.   private static final String COMMA = ",";
 4.   
 5.   public String getCountry(){ return COUNTRY; }
 6.   
 7.   public String getFullAddress(){
 8.     return getStreet() + EOL_STRING +
 9.       getCity() + COMMA + SPACE + getRegion() +
10.       SPACE + getPostalCode() + EOL_STRING +
11.       COUNTRY + EOL_STRING;
12.   }
13. }

Example 1.6 USPhoneNumber.java 0

 1. public class USPhoneNumber extends PhoneNumber{
 2.   private static final String COUNTRY_CODE = "01";
 3.   private static final int NUMBER_LENGTH = 10;
 4.   
 5.   public String getCountryCode(){ return COUNTRY_CODE; }
 6.   
 7.   public void setPhoneNumber(String newNumber){
 8.     if (newNumber.length() == NUMBER_LENGTH){
 9.       super.setPhoneNumber(newNumber);
10.     }
11.   }
12. }

The generic framework from AddressFactory, Address, and PhoneNumber makes it easy to extend the system to support additional countries. With each additional country, define an additional Concrete Factory class and a matching Concrete Product class. These are files for French address information.

Example 1.7 FrenchAddressFactory.java 0

1. public class FrenchAddressFactory implements AddressFactory{
2.   public Address createAddress(){
3.     return new FrenchAddress();
4.   }
5.   
6.   public PhoneNumber createPhoneNumber(){
7.     return new FrenchPhoneNumber();
8.   }
9. }

Example 1.8 FrenchAddress.java 0

 1. public class FrenchAddress extends Address{
 2.   private static final String COUNTRY = "FRANCE";
 3.   
 4.   public String getCountry(){ return COUNTRY; }
 5.   
 6.   public String getFullAddress(){
 7.     return getStreet() + EOL_STRING +
 8.       getPostalCode() + SPACE + getCity() +
 9.       EOL_STRING + COUNTRY + EOL_STRING;
10.   }
11. }

Example 1.9 FrenchPhoneNumber.java 0

 1. public class FrenchPhoneNumber extends PhoneNumber{
 2.   private static final String COUNTRY_CODE = "33";
 3.   private static final int NUMBER_LENGTH = 9;
 4.   
 5.   public String getCountryCode(){ return COUNTRY_CODE; }
 6.   
 7.   public void setPhoneNumber(String newNumber){
 8.     if (newNumber.length() == NUMBER_LENGTH){
 9.       super.setPhoneNumber(newNumber);
10.     }
11.   }
12. }

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020