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).