Java Reference
In-Depth Information
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 -
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
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
1. public abstract class Address {
2. private String street;
3. private String city;