-
Notifications
You must be signed in to change notification settings - Fork 15
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:
- The product. In our example this is the abstract class Pizza
- The concrete product. In our example these are the sub-classes that extend Pizza
- By having subclasses all our Concrete pizza now share a common interface for creation.
- The creator. In our example this is the abstract class PizzaStore. It contains an abstract createPizza() method that subclasses must implement.
- All pizza stores now share a common interface to create a Pizza. Because pizza is abstract our code is more loosely coupled.
- The concrete creator: Returns a concrete product.