Factory Method Pattern
Overview
Define an interface for creating an object, but let subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation to subclasses.
Participants
- defines the interface of objects the factory method creates.
- implements the Product interface.
- this participant can not be read-only.
- declares the factory method, which returns an object of type Product. Creator
may also define a default implementation of the factory method that returns
a default Concrete Product object.
- may call the factory method to create a Product object.
- this participant can not be read-only.
- overrides the factory method to return an instance of a Concrete Product.
- this participant can not be read-only.
- this participant can not be an interface.
Parameters
- in the "Factory method" field you can specify the name of a Creator's method
which returns an object of type Product.
- in the "Factory method arguments" field you can specify parameters when
calling the factory method (for example,
int i, boolean b.) The
pattern will create a constructor in the Concrete product with these parameters,
so the factory method (in Concrete creator) will return an instance of Concrete
product initialized with the specified parameters.
- the Creator may define a default implementation of the factory method that
returns a default Concrete Product object. This property selects whether to
provide this default implementation or not.
- when selected, will create special JavaDoc links in the code between pattern
participants, describing their relationships.
Applicability
Use the Factory Method pattern 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 several helper subclasses, and you want to localize the
knowledge of which helper subclass is the delegate.