Factory Method Pattern

Summary

  • The Factory Method pattern is a way of creating objects, but letting subclasses decide exactly which class to instantiate.
  • The Factory Method pattern is a lightweight pattern that achieves independence from application-specific classes. The client programs to the interface and lets the pattern sort out the rest.

Class diagram: (see Factory Method Pattern code review)

Factory Method Pattern class diagram of sample code download

Usage

Use the Factory Method pattern when:

  • Flexibility is important.
  • Objects can be extended in subclasses.
  • There is a specific reason why one subclass would be chosen over another (this logic forms part of the Factory Method).
  • A client delegates responsibilities to subclasses in parallel hierarchies.