|
|
Factory Method Pattern
Intent
“Define interface for creating an
object, but let subclasses decide which class to instantiate.” - GoF
Motivation
Encapsulates
knowledge of which subclass to create, and moves this out of the
framework.
Applicability
Use Factory Method
when:
-
A class can't anticipate the
class of objects it must create.
-
A class wants its subclasses
to
specify the objects it creates.
-
Classes delegate
responsibility to one of the helper subclasses, and you want to
localize the knowledge of which helper subclass is the delegate.
Structure
-
Product defines the
interface of objects the factory method creates (MonthlyCommand).
-
ConcreteProduct implements the Product interface (Annuity, Employee,
LifeInsurance).
-
Creator declares the
factory method, which returns an object of type Product. May also
define a default implementation of the factory method that returns a
default ConcreteProduct object. May call the factory method to create a
Product object (used in my example).
-
Concrete
Creator overrides the factory method to return an instance of
ConcreteProduct. (Not used in my example.)
Consequences
-
Eliminates
need to bind app-specific classes into code. Code only deals
with Product interface.
-
May have
to subclass Creator just to create a particular ConcreteProduct. Not
in my case – my design is flexible.
-
Provides
hooks for subclasses.
-
Connects
parallel class hierarchies.
Implementation
Behavioral Patterns - Command
Pattern
|