Factory Method
Intent
Define an interface for creating an object, but let subclasses decide
which class to instantiate. Factory Method lets a class defer
instantiation to subclasses.
Structure
-
Product -
defines the interface for objects created by the factory method.
-
Concrete Product -
implements the Product interface.
-
Creator -
declares the factory method and may provide a default implementation.
-
Concrete Creator -
implements or overrides the factory method to return a Concrete
Product.
Notes
-
The Factory Method pattern, like the Template Method pattern, is a
pattern for using implementation inheritance.
It can be viewed as a Template Method pattern in which one or more of
the algorithm steps that is deferred to subclasses involves creating
objects.
However the pattern terminology is different.
The factory method itself corresponds to either a Primitive Operation or
a Hook Operation in the Template Method pattern.
-
The Prototype design pattern can be used as an alternative to the
Factory Method design pattern.
The Creator can declare a protected variable of type Product and the
Concrete Creator subclasses can initialize this variable with
different prototype objects.
-
If the Creator classes use families of created objects then the
resulting pattern is the Abstract Factory pattern.
An Abstract Factory can use either Factory Methods or Prototypes.