Pattern: Factory Method

by Uri Moszkowicz

Synopsis

The factory method pattern is used to defer instantiation to subclasses. Using this method, a class need only know when to instantiate a class, not what kind of subclass to create.

Context

This pattern addresses a problem found in the AbtractButton swing class. Its subclasses JCheckBox and JRadioButton want to display different icons when clicked. It uses a factory method to let its subclasses decided which icon to display.



Forces

There are two primary forces

Solution

There are four main actors in the factory method:


Taken from dofactory
As shown, the creator calls the FactoryMethod() to get an object to be determined by a subclass. The creator only needs to know that it will be returning an object of type Product. A subclass, named ConcreteCreator here, then overloads the FactoryMethod() to return ConcreteProduct instead of Product.

Consequences

+

-

Implementation

There are two variations of this pattern.

  1. The factory method instantantiates the ConcreteProducts
  2. Subclasses of the Creator overload the factory method to instantiate Concrete Products
Both can be found in this example.

Related Patterns