Factory Method

Defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

classDiagram
    class Creator {
        +factoryMethod() Product
        +someOperation()
    }
    class ConcreteCreatorA {
        +factoryMethod() Product
    }
    class ConcreteCreatorB {
        +factoryMethod() Product
    }
    class Product {
        <<interface>>
        +doStuff()
    }
    class ConcreteProductA {
        +doStuff()
    }
    class ConcreteProductB {
        +doStuff()
    }

    Creator <|-- ConcreteCreatorA
    Creator <|-- ConcreteCreatorB
    Product <|.. ConcreteProductA
    Product <|.. ConcreteProductB
    ConcreteCreatorA ..> ConcreteProductA
    ConcreteCreatorB ..> ConcreteProductB

When to use

Use to provide a hook for a user to extend the internal components of a library or framework. Use when a class can’t anticipate the class of objects it must create.

Explanation

Problem

Imagine you’re creating a logistics management application. The first version of your app can only handle transportation by trucks, so the bulk of your code lives inside the Truck class. Later, your app becomes popular, and you need to add sea logistics. Adding Ship into the app would require making changes to the entire codebase.

Solution

The Factory Method pattern suggests that you replace direct object construction calls (using the new operator) with calls to a special factory method. The objects are still created via the new operator, but it’s being called from within the factory method. Subclasses can alter the class of objects being returned.

Real world problem

  1. Logistics App: Truck Delivery vs Sea Delivery. The Logistics class declares a createTransport method. RoadLogistics returns a Truck, SeaLogistics returns a Ship.
  2. Cross-Platform UI: A dialog box may need to render different styles of buttons depending on the OS (Windows vs Web vs Mobile).
  3. Document Export: An application supports exporting documents to various formats (HTML, PDF, Markdown). Each format has its own generator class created by a factory.

Pros and Cons

Pros Cons
- Decoupling: Avoids tight coupling between the creator and the concrete products.
- Single Responsibility Principle: You can move the product creation code into one place in the program, making the code easier to support.
- Open/Closed Principle: You can introduce new types of products into the program without breaking existing client code.
- Complexity: The code may become more complicated since you need to introduce a lot of new subclasses to implement the pattern. The best case scenario is when you’re introducing the pattern into an existing hierarchy of creator classes.

Comparison

  • Abstract Factory: Factory Method is often a step towards Abstract Factory. Abstract Factory relies on a set of Factory Methods.
  • Prototype: Doesn’t require subclassing, but often requires an “Initialize” operation. Factory Method requires subclassing (Concrete Creators).
  • Template Method: Factory Methods are often called within Template Methods.

Code example

Typescript

Php