Skip to content

Factory Method Pattern

Brooks Johnson edited this page Jun 24, 2022 · 4 revisions

Intent: To define an interface for creating an object. But we let subclasses decide which class to instantiate. The factory method lets class defer instantiation to a subclass.

When to use

  • A class can not anticipate the object it must create
  • A class wants its subclasses to determine the objects they create

Participants:

  1. The product. In our example this is the abstract class Pizza
  2. The concrete product. In our example these are the sub-classes that extend Pizza
    1. By having subclasses all our Concrete pizza now share a common interface for creation.
  3. The creator. In our example this is the abstract class PizzaStore. It contains an abstract createPizza() method that subclasses must implement.
    1. All pizza stores now share a common interface to create a Pizza. Because pizza is abstract our code is more loosely coupled.
  4. The concrete creator: Returns a concrete product.

Clone this wiki locally