Abstract Factory Design Pattern
Creational pattern. Creational design patterns are concerned with object creation.
Intent: "Provide an interface for creating families of related or dependent objects without specifying their concrete classes." [GoF]
Open in the interactive referenceDownload the PDF reference
Intent
The intent of the Abstract Factory design pattern is to:
"Provide an interface for creating families of
related or dependent objects
without specifying their concrete classes."
[GoF]
See Problem and Solution
sections for a more structured description of the intent.
-
The Abstract Factory design pattern solves problems like:
- How can a class be independent of how the objects it requires are created?
- How can different families of related or dependent objects be created?
-
An inflexible way is to create objects
directly within the class
(
Client) that requires the objects. This commits the class to particular objects and makes it impossible to change the instantiation later independently from (without changing) the class. -
The Abstract Factory pattern describes
how
to solve such problems:
-
Provide an interface for
creating families of related or dependent
objects
without specifying their concrete classes:
AbstractFactory | createProductA(),createProductB(),… -
The process of object creation
(
new ProductA1(), for example) is abstracted by referring to an interface (delegating to a factory object):factory.createProductA().
There is no longer anything in the client code that instantiates a concrete class.
-
Provide an interface for
creating families of related or dependent
objects
Problem
The Abstract Factory design pattern solves problems like:
How can a class be independent
of how the objects it requires are created?
How can different families of
related or dependent objects be created?
See Applicability section for all problems Abstract Factory can solve.
See Solution section for how Abstract Factory solves the problems.
-
An inflexible way is to create objects
(
new ProductA1(),new ProductB1()) directly within the class (Client) that requires (uses) the objects. -
This commits (couples) the class to particular objects
and makes it impossible to change the instantiation
later independently from
(without having to change) the class.
It stops the class
from being reusable if other objects are required,
and it makes the class hard to test
because real objects can't be replaced
with mock objects.
"Instantiating look-and-feel-specific classes of widgets throughout the application makes it hard to change the look and feel later." [GoF, p87]
Furthermore, "Specifying a class name when you create an object commits you to a particular implementation instead of a particular interface." [GoF, p24] - That's the kind of approach to avoid if we want that a class is independent of how its objects are created.
-
For example, designing reusable classes that require (depend on) other objects.
A reusable class should avoid creating the objects it requires directly (and often it doesn't know at compile-time which class to instantiate) so that it can request the objects it requires at run-time (from a factory object). -
For example, supporting different look-and-feels in a
Web/GUI application.
Instantiating look-and-feel-specific classes throughout an application should be avoided so that a look and feel can be selected and exchanged at run-time.
Background Information
- The Swing GUI toolkit of the Java platform, for example, lets you create (and switch between) different families of objects to support different look-and-feels (like Java, Windows, and custom look-and-feels).
Solution
The Abstract Factory design pattern provides a solution:
Encapsulate creating a family of objects
in a separate
factory object.
A class delegates object creation
to a factory object
instead of instantiating concrete classes directly.
Describing the Abstract Factory design in more detail is
the theme of the following sections.
See Applicability section for all problems Abstract Factory can solve.
-
The key idea in this pattern is to abstract
the process of object
creation.
[BGI]
The process of object creation (new ProductA1(), for example) is abstracted by referring to an interface (delegating to a factory object):factory.createProductA().
There is no longer anything in the client code that instantiates a concrete class.
"Creational patterns ensure that your application is written in terms of interfaces, not implementations." [GoF, p18] -
Define separate
factoryobjects:
-
For all supported families of objects,
define a common interface for creating a family of objects
(
AbstractFactory | createProductA(),createProductB(),…). -
Define classes (
Factory1,…) that implement the interface.
-
For all supported families of objects,
define a common interface for creating a family of objects
(
-
This enables compile-time flexibility (via inheritance).
The way objects are created can be implemented and changed independently from clients by defining new (sub)classes. -
A class (
Client) delegates the responsibility for creating objects to afactoryobject (factory.createProductA(),factory.createProductB(),…).
-
This enables run-time flexibility (via object composition).
A class can be configured with a factory object, which it uses to create objects, and even more, the factory object can be exchanged dynamically.
Background Information
- "Not only must we avoid making explicit constructor calls; we must also be able to replace an entire widget set easily. We can achieve both by abstracting the process of object creation." [GoF, p48]
- Abstract Factory is often referred to as Factory or Factory Object because all design patterns do some kind of abstraction. The Strategy pattern, for example, abstracts and encapsulates an algorithm. "Abstraction and encapsulation are complementary concepts [...] For abstraction to work, implementations must be encapsulated." [GB07, p51]
-
For simple applications that do not need
exchangeable families of objects, a common implementation of the
Abstract Factory pattern is just a concrete factory
class that acts as both the interface and
implementation
(see Implementation).
"Also note thatMazeFactoryis not an abstract class; thus it acts as both the AbstractFactory and the ConcreteFactory. This is another common implementation for simple applications of the Abstract Factory pattern." [GoF, p94]
Motivation
Consider the left design (problem):
-
Hard-wired object creation.
-
Creating objects is implemented (hard-wired)
directly within a class
(
Client). - This makes it hard to change the way objects are created (which concrete classes get instantiated) independently from (without having to change) the class.
-
Creating objects is implemented (hard-wired)
directly within a class
(
-
Distributed object creation.
- Creating objects is distributed across the classes of an application.
Consider the right design (solution):
-
Encapsulated object creation.
-
Creating objects is implemented (encapsulated)
in a separate class
(
Factory1). - This makes it easy to change the way objects are created (which concrete classes get instantiated) independently from (without having to change) clients.
-
Creating objects is implemented (encapsulated)
in a separate class
(
-
Centralized object creation.
-
Creating objects is centralized
in
a single
Factory1class.
-
Creating objects is centralized
in
a single
Applicability
Design Problems
-
Creating Objects
- How can a class be independent of how the objects it requires are created?
-
How can a class request the objects it requires
(from a factory object)
instead of creating the objects directly? - How can a class delegate object creation to a factory object?
- How can a class be configured with a factory object?
-
Creating Different Object Families
- How can families of related or dependent objects be created?
-
How can be ensured that a
family of related or dependent objects
is created and used together (consistent object families)? - How can an application be configured with a family of objects?
- How can a family of objects be selected and exchanged at run-time?
Refactoring Problems
-
Inflexible Code
- How can instantiating concrete classes throughout an application (compile-time implementation dependencies) be refactored?
-
How can object creation that is distributed across
an application
be centralized? Move Creation Knowledge to Factory (68) [JK05]
Testing Problems
-
Unit Testing
- How can the objects a class requires be replaced with mock objects so that the class can be unit tested in isolation?
Structure
Static Class Structure
-
Client-
Requires
ProductAandProductBobjects. -
Refers to the
AbstractFactoryinterface to createProductAandProductBobjects and is independent of how the objects are created (which concrete classes are instantiated). -
Maintains a reference
(
factory) to anAbstractFactoryobject.
-
Requires
-
AbstractFactory- Defines an interface for creating a family of product objects.
-
Factory1,…-
Implement the
AbstractFactoryinterface by creating and returning the objects.
-
Implement the
Dynamic Object Collaboration
-
In this sample scenario,
a
Clientobject delegates creating product objects to aFactory1object.
Let's assume that theClientis configured with aFactory1object. -
The interaction starts with the
Clientthat callscreateProductA()on the installedFactory1object. -
Factory1creates aProductA1object and returns (a reference to) it to theClient. -
Thereafter, the
ClientcallscreateProductB()onFactory1. -
Factory1creates aProductB1object and returns it to theClient. -
The
Clientcan then use theProductA1andProductB1objects as required. -
See also Sample Code / Example 1.
Consequences
Advantages (+)
-
Avoids compile-time implementation dependencies.
- Instead of instantiating concrete classes directly, clients delegate instantiation to a separate factory object.
-
Ensures creating consistent object families.
- When an application supports creating multiple families of related objects, it must be ensured that a family of related objects is created and used together (see Sample Code / Example 3).
-
Makes exchanging whole object families easy.
- Because a factory object encapsulates creating a complete family of objects, the whole family can be exchanged by exchanging the factory object.
Disadvantages (–)
-
Requires extending the
Factoryinterface to extend an object family.-
The
Factoryinterface must be extended to extend a family of objects (to support new kinds of objects).
-
The
-
Introduces an additional level of indirection.
- The pattern achieves flexibility by introducing an additional level of indirection (clients delegate instantiation to a separate factory object), which makes clients dependent on a factory object.
Implementation
Implementation Issues
Variant 1: Abstract Factory
Creating different families of objects.
- Interface and implementation are cleanly separated.
- This is the way to implement the Abstract Factory pattern for applications that support creating families of related or dependent objects (see Sample Code / Example 1).
- "An application typically needs only one instance of a ConcreteFactory per product family. So it's usually best implemented as a Singleton(127)." [GoF, p90] See Sample Code / Example 3.
Variant 2: Concrete Factory
Creating (a family of) objects.
- Interface and implementation are not cleanly separated.
-
The concrete
Factory1class acts as both interface and implementation (it abstracts and implements object creation). - This is a common way to implement the Abstract Factory pattern for applications that do not need to create families of objects but want to be independent of how their objects are created (see Sample Code / Example 2).
-
"Also note that
MazeFactoryis not an abstract class; thus it acts as both the AbstractFactory and the ConcreteFactory. This is another common implementation for simple applications of the Abstract Factory pattern." [GoF, p94] -
"Notice that the [concrete]
MazeFactoryis just a collection of factory methods. This is the most common way to implement the Abstract Factory pattern." [GoF, p94]
Sample Code 1
Basic Java code for implementing the sample UML diagrams.
1 package com.sample.abstractfactory.basic1;
2 public class MyApp {
3 public static void main(String[] args) {
4 // Creating a Client object
5 // and configuring it with a factory object.
6 Client client = new Client(new Factory1());
7 // Calling an operation on the client.
8 System.out.println(client.operation());
9 }
10 }
Client : Delegating creating objects to a factory object.
Factory1: Creating a ProductA1 object.
Factory1: Creating a ProductB1 object.
Hello World from ProductA1 and ProductB1!
1 package com.sample.abstractfactory.basic1;
2 public class Client {
3 private ProductA productA;
4 private ProductB productB;
5 private AbstractFactory factory;
6
7 public Client(AbstractFactory factory) {
8 this.factory = factory;
9 }
10 public String operation() {
11 System.out.println("Client : Delegating creating objects to a factory object.");
12 productA = factory.createProductA();
13 productB = factory.createProductB();
14 // Doing something appropriate on the created objects.
15 return "Hello World from " + productA.getName() + " and "
16 + productB.getName() + "!";
17 }
18 }
1 package com.sample.abstractfactory.basic1;
2 public interface AbstractFactory {
3 ProductA createProductA();
4 ProductB createProductB();
5 }
1 package com.sample.abstractfactory.basic1;
2 public class Factory1 implements AbstractFactory {
3 public ProductA createProductA() {
4 System.out.println("Factory1: Creating a ProductA1 object.");
5 return new ProductA1();
6 }
7 public ProductB createProductB() {
8 System.out.println("Factory1: Creating a ProductB1 object.");
9 return new ProductB1();
10 }
11 }
1 package com.sample.abstractfactory.basic1;
2 public class Factory2 implements AbstractFactory {
3 public ProductA createProductA() {
4 System.out.println("Factory2: Creating a ProductA2 object.");
5 return new ProductA2();
6 }
7 public ProductB createProductB() {
8 System.out.println("Factory2: Creating a ProductB2 object.");
9 return new ProductB2();
10 }
11 }
*******************************************************
Product inheritance hierarchy.
*******************************************************
1 package com.sample.abstractfactory.basic1;
2 public interface ProductA {
3 String getName();
4 }
1 package com.sample.abstractfactory.basic1;
2 public class ProductA1 implements ProductA {
3 public String getName() {
4 return "ProductA1";
5 }
6 }
1 package com.sample.abstractfactory.basic1;
2 public class ProductA2 implements ProductA {
3 public String getName() {
4 return "ProductA2";
5 }
6 }
1 package com.sample.abstractfactory.basic1;
2 public interface ProductB {
3 String getName();
4 }
1 package com.sample.abstractfactory.basic1;
2 public class ProductB1 implements ProductB {
3 public String getName() {
4 return "ProductB1";
5 }
6 }
1 package com.sample.abstractfactory.basic1;
2 public class ProductB2 implements ProductB {
3 public String getName() {
4 return "ProductB2";
5 }
6 }
*******************************************************
Unit test classes.
*******************************************************
1 package com.sample.abstractfactory.basic1;
2 import junit.framework.TestCase;
3 public class ClientTest extends TestCase {
4 // Creating a Client object
5 // and configuring it with a mock factory.
6 Client client = new Client (new FactoryMock());
7
8 public void testOperation() {
9 assertEquals("Hello World from ProductAMock and ProductBMock!",
10 client.operation());
11 }
12 // More tests ...
13 }
1 package com.sample.abstractfactory.basic1;
2 public class FactoryMock implements AbstractFactory {
3 public ProductA createProductA() {
4 return new ProductAMock();
5 }
6 public ProductB createProductB() {
7 return new ProductBMock();
8 }
9 }
1 package com.sample.abstractfactory.basic1;
2 public class ProductAMock implements ProductA {
3 public String getName() {
4 return "ProductAMock";
5 }
6 }
1 package com.sample.abstractfactory.basic1;
2 public class ProductBMock implements ProductB {
3 public String getName() {
4 return "ProductBMock";
5 }
6 }
Not included on this page: Related Patterns. See the GoF Design Patterns Reference (PDF) for the complete description.