AlgoViz

Factory method

medium 60 min

A fixed workflow with one open step that creates an object.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:53

Factory method

1:04Reel

Factory method in one picture
Factory method in one picture

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

Factory method vs abstract factory

0:32Reel

Theory

Read or listen first. About 2 min.

What it is

Factory Method is a creational pattern. A base class, the creator, contains a workflow that needs an object. It gets the object from a method of its own, and subclasses override that method. So the base class uses an object whose class it does not know.

The pattern has two halves that are easy to mix up: the method that creates, and the workflow that uses the result. Without the workflow there is no reason for a base class, and a function does the job.

Think of a chain of restaurants. Head office writes how a burger is made and served. Each place decides which filling it uses, paneer here, beef there. The guest orders a burger.

Why it exists

A constructor call names a class. Code full of them can not be extended without being edited, and can not be tested without the real thing.

Frameworks need it most. Their authors write the workflow years before anyone writes the product. The hook method is how the two meet.

In interviews the word factory appears in nearly every object design round. Candidates who can tell a simple factory, a factory method and an abstract factory apart, and can say when none is needed, stand out.

A short history

  1. 1994

    The book "Design Patterns" by Gamma, Helm, Johnson and Vlissides describes Factory Method among the creational patterns, next to Abstract Factory, Builder, Prototype and Singleton.

  2. Java 5 (2004)

    Iterable and ThreadFactory join the Java library: one method that creates an iterator, and one object that creates threads on demand, instead of calls to new Thread.

  3. Java 6

    AbstractExecutorService gets newTaskFor, a protected factory method with a default, so that subclasses can supply their own kind of task.

  4. 18 April 2007

    PEP 3119 is created. It brings abstract base classes to Python, which make a missing override an error at creation.

Words to know

Factory method
A method that creates an object and can be overridden.
Creator
The class that declares the factory method and usually uses its result.
Product
The interface of what is created.
Simple factory
One function or class that decides by a value. Not a pattern of the book.
Static factory method
A named way to get an object of a class, such as of or from_text.
Abstract factory
An object with several creating methods whose products fit together.
Registry
A map from a name to a function that creates.
Hook
A method of a base class that is meant to be overridden.
Parallel hierarchies
Two class trees that grow together, one creator for each product.
Virtual constructor
An older name for the idea, used in the C++ FAQ: a method that has the effect of a constructor chosen at run time.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Client requests operation. The client calls the workflow of the creator without knowing which concrete class will be made.

Understand it

Start here

One recipe, many moulds

A workshop sells candles. Melting, pouring, cooling and cutting the wick are the same everywhere. Only the mould differs from branch to branch. The Factory Method pattern is that workshop in code: the steps are written once, and the one step that creates something is left open for each branch.

The candle workshop
hill? tallharbour? roundchurch? tallelse? tall

Compare the first and the third picture: the decision moved from a list that one person edits to an open line that each branch fills.

Four roles

  • Product

    The interface that all created objects share: Candle, Vehicle, Document. The workflow and the client know only this.

  • Concrete product

    Pillar, BmwM5, InvoicePdf. They do not know who created them.

  • Creator

    Declares the factory method and usually holds the workflow that uses the product. The method is abstract or has a default.

  • Concrete creator

    Overrides the factory method and returns one kind of product, with everything that is special about building it.

The pattern as classes

uses«abstract»Workshop+ make(): the recipe# takeMould(): Candle«interface»Candle+ burnHours(): int

1/3The abstract half

The creator works with the product interface. Both are abstract, and the arrow between them names no concrete class.

usesextends (is a)implements

Two trees side by side. Each new leaf on the right usually brings a new leaf on the left. Remember that: it is also the price.

Why

What goes wrong without it

Calling constructors all over the program ties each caller to concrete classes. When a new kind appears, or a constructor gets another parameter, edits spread through the code. The first repair is one method with conditions. It helps, and it has its own disease.

Python
class Pillar:    burn_hours = 40class Floating:    burn_hours = 4class Workshop:    def make(self, branch):        if branch == "hill":            candle = Pillar()        elif branch == "harbour":            candle = Floating()        else:            candle = Pillar()               # somebody had to decide something        return f"{type(candle).__name__} cooled, wick cut, boxed"    def price_tag(self, branch):        if branch == "hill":                # the same question again            return "40 hours"        return "4 hours"                    # and another defaultshop = Workshop()print(shop.make("forest"), "|", shop.price_tag("forest"))
Run it for the forest. The candle burns 40 hours, the price tag says 4, and nothing complains.
Edit and run it in your browser

Two methods ask the same question and have different defaults. The kind of a candle is not written in one place, it is spread over conditions. The design below shows what depends on what.

The design that hurts

newnewWorkshop+ make(branch): 3 ifs+ priceTag(branch): 2 ifsPillar+ burn()Floating+ burn()

1/2Two kinds

The workshop knows both classes.

depends on

The class with the stable recipe depends on the classes that change most often. The pattern turns those arrows around.

The idea

Call a method that does not exist yet

In the base class the recipe calls take_mould(). The base class has no body for it. Every subclass supplies one. The steps stay in one place and the choice moves into the subclass.

Python
from abc import ABC, abstractmethodclass Candle(ABC):    @abstractmethod    def burn_hours(self): ...class Pillar(Candle):    def burn_hours(self): return 40class Floating(Candle):    def burn_hours(self): return 4class Workshop(ABC):    def make(self):                         # the recipe card        candle = self.take_mould()          # the open line        name = type(candle).__name__        return f"{name} cooled, wick cut, boxed | {candle.burn_hours()} hours"    @abstractmethod    def take_mould(self) -> Candle: ...     # the factory methodclass HillBranch(Workshop):    def take_mould(self): return Pillar()class HarbourBranch(Workshop):    def take_mould(self): return Floating()class Star(Candle):                         # later, a new branch    def burn_hours(self): return 6class ForestBranch(Workshop):    def take_mould(self): return Star()for branch in (HillBranch(), HarbourBranch(), ForestBranch()):    print(branch.make())try:    Workshop()except TypeError as error:    print("the card alone makes nothing:", type(error).__name__)
The forest branch was added below the rest. Nothing above it was edited.
Edit and run it in your browser

One call, seen from inside

The workshop part and the hill part are one object. The call goes down to the subclass and the product comes back up as the interface type.

How to build it

StepDoExample
1Write the product interface from what the workflow needsCandle.burn_hours()
2Write the concrete productsPillar, Floating
3Write the creator: the workflow, and an abstract factory methodWorkshop.make, take_mould
4Write one concrete creator per variantHillBranch
5Let the client work with the creator typebranch.make()
6Choose the creator in one placemain, a configuration, a registry
Step 6 is missing in most descriptions. Somebody must still choose. The pattern does not remove that decision, it makes it one line.

Principles

What it gives you

  • Open for new kinds

    A new kind is new classes. The existing creators are not edited. See open closed.

  • Dependencies turned around

    The workflow depends on Candle, not on Pillar. See dependency inversion.

  • One home for building

    The details of building one kind sit in one creator.

  • A seam for tests

    A test creator can return a small fake product.

What a new kind costs

1 product+1 creator+1 line where it is chosen1 \text{ product} + 1 \text{ creator} + 1 \text{ line where it is chosen}
Not zero changes, and not one file. But all of it is new code, except for a single line.

Who creates? A decision

The full pattern is one leaf of five. Say which leaf you are on and why.

A report job must write to PDF today and to Markdown next month. The steps before and after are the same. How do you create the document?

Breaksif in the job, with a default
How
if kind == 'pdf': ... else: ...
Limit
The else produces Markdown for every typing mistake, and the same if appears in the test, the mail and the preview.
Choose when
Never with a silent else.
WorksA publisher with a factory method
How
PdfPublisher and MarkdownPublisher override create_document.
Limit
Two classes per format. Heavy, if only this object differs.
Choose when
When formats also differ in other steps, such as page numbers or signing.
StrongOne publisher that receives a function
How
Publisher(make_document=PdfDocument), chosen in main from a map of known formats.
Limit
No place for a second difference. Then grow into the pattern.
Choose when
When the created object is the only difference.

Use it when

  • A workflow is fixed and one object in it varies
  • The exact class is not known to the base class
  • Users of your framework must plug in their own classes
  • Knowledge about building one kind should have one home
  • Return the interface, and let one creator take a parameter for close relatives

Leave it when

  • There is one product
  • The constructor call is trivial and will stay so
  • Kinds differ in numbers, not in behaviour
  • A function or a simple factory is enough
  • Callers would cast the product back to its class

Relatives

Simple factory, factory method, abstract factory

Simple factoryFactory methodAbstract factory
FormOne function or class with a decisionAn overridable methodAn object with several creating methods
Chosen byA valueWhich subclass you haveWhich factory object you were given
MakesOne productOne product inside a workflowProducts that fit together
MechanismCondition or mapInheritanceComposition
New kindEdit one placeNew subclassNew factory class
Book pattern?NoYesYes
An interface with a single create method, passed to the client, is often called factory method. By its form it is a small abstract factory: the client holds it and does not inherit from it.
PatternQuestion it answers
Factory methodWhich class, decided by a subclass
BuilderHow to put a complex object together, step by step
PrototypeWhich example to copy
Template methodWhich steps vary. A factory method is often one of its hooks
StrategyWhich behaviour to use, passed in from outside
SingletonHow to have only one

Summary

The whole topic in one minute.

Write the steps once, in a creator. Where the steps need an object, call a method that subclasses override. Clients see the creator and the product interface, so a new kind is a new product, a new creator and one line of choice.

Then ask whether you need the tree at all. If a value chooses, use a simple factory or a sealed registry. If only the object differs, pass a function. Keep the promises of creation in writing: ready, new or shared, cleaned up on failure, and never called from a constructor.

  • A fixed workflow calls an abstract creating method. Subclasses decide what it returns.
  • Product, concrete product, creator, concrete creator. The client knows the first and the third.
  • A simple factory decides by a value in one place. A factory method decides by which subclass you have.
  • A new kind is new classes and one line of choice. Nobody removes the choice.
  • If only the object varies, pass a function. Inheritance is for several differences.
  • The override must keep the contract: ready, never empty, new or shared as promised.

Sources