# Factory MethodFifty lines of spawn code and one new Wolf() in the middle. Learn how Factory Method lets the parent keep the steps while each subclass picks the class, and how it differs from its look-alikes.

Your game's spawn code is fifty lines of timing, placement and difficulty. The forest level loves
it: wolves arrive in waves, right on cue. Now the designers want an ice level, with yetis. And
somewhere in those fifty lines, it says `new Wolf()`. Do you copy all fifty lines, to change one
word? There's a better way, and it's called the **Factory Method** pattern.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows
it section by section, with diagrams and a little extra depth.

{{< lesson-video youtube="XDg5dkRIZj8" title="Factory Method" >}}

## Fifty lines, one word

Copying works today. But the next fix to the timing has to be made in two places, and then in three
when a lava level arrives. One `new` has welded a whole method to one class.

## Match day

Think of match day in a sports league. Every club runs the same routine. Open the gates, play the
anthem, the mascot runs out, and kick off. The league decides when the mascot appears. Each club
decides which mascot: one brings a bear, another an eagle.

> **The league decides when. The club decides what.**

In code, the league is the **creator**, the class that owns the routine. The mascot is the
**product**. And the step that makes it is the **factory method**. When a new club joins, the league
doesn't rewrite the routine: the new club brings its own mascot.

```mermaid {alt="Match day mapped onto code: the league's routine is the creator's method (spawnWave); the mascot slot is the factory method (createEnemy); each club is a subclass (ForestLevel, IceLevel); the mascot is the product (Enemy)." caption="Match day, mapped onto the code."}
flowchart LR
  A["the league's routine"] --> A2["Level.spawnWave()"]
  B["the mascot slot"] --> B2["createEnemy()"]
  C["each club"] --> C2["ForestLevel, IceLevel"]
  D["the mascot"] --> D2["Enemy"]
  class A2 c1
  class B2 hl
  class D2 c4
```

## The obvious version: just `new` it

Here's the forest version. The level spawns a wave, and for each enemy it makes a new wolf, places
it, and keeps it.

```java
public class Level {
    private final List<Enemy> enemies = new ArrayList<>();

    public void spawnWave(int size) {
        for (int i = 0; i < size; i++) {
            Enemy e = new Wolf();
            e.placeAt(randomSpot());
            enemies.add(e);
        }
    }
}
```

An enemy is anything you can place on the map. That's the role every enemy plays.

```java
public interface Enemy {
    void placeAt(Spot spot);
}
```

With one level, this is the right code. It's direct, and there's nothing to look up. Spawning,
placing and keeping enemies is the part worth writing once. Which enemy to make is the only part
that changes. (The real method in the hook is fifty lines; the five shown here stand in for them.)

## Why it breaks

Then the ice level arrives, and the `new` line grows a branch on the theme. Then lava arrives, and
it grows another.

```java
Enemy e;
if (theme.equals("ice")) e = new Yeti();
else if (theme.equals("lava")) e = new FireImp();
else e = new Wolf();
```

The boss spawner makes the same choice, in its own copy of the chain. Every new level means finding
both. And the level class now imports every enemy in the game. A modder who wants a swamp level has
to edit it, and can't. It's a league manual that lists every club's mascot, and gets reprinted
whenever a club joins.

```mermaid {alt="Level's spawn code depends on every enemy class: Wolf, Yeti and FireImp. A new swamp level forces edits in spawnWave and spawnBoss, and a mod jar can't make them." caption="The shared code knows every kind."}
flowchart LR
  L["Level.spawnWave<br/>+ spawnBoss"] --> W["Wolf"]
  L --> Y["Yeti"]
  L --> F["FireImp"]
  S["swamp-mod.jar"] -. "can't add a level" .-> L
  class L bad
  class W c6
  class Y c5
  class F c2
```

This is the creation-side cousin of [Switch Statements](/code-smells/switch-statements/): a
choice on a kind, repeated and growing.

## The key idea: move the `new` behind a method

The steps aren't the problem. One word is: the `new`, welded into the middle of shared code.

So replace it with a call. The level asks for an enemy, and leaves the choice to a method its
subclasses override:

`Enemy e = createEnemy();`

The Gang of Four describe it (*Design Patterns*, 1994, paraphrased) as an interface for creating an
object, where subclasses decide which class to make. Notice that nothing moved out of the level.
The method that creates the enemy sits right beside the code that uses it: there's no separate
factory class.

> **The parent decides when. The subclass decides what.**

## Building it

Here's the level now. It's abstract. `spawnWave` is the same loop, except that it calls
`createEnemy`. And `createEnemy` is declared, but not written. It returns the role, an `Enemy`, so
the loop never names a real class.

```java
public abstract class Level {
    private final List<Enemy> enemies = new ArrayList<>();

    public void spawnWave(int size) {
        for (int i = 0; i < size; i++) {
            Enemy e = createEnemy();
            e.placeAt(randomSpot());
            enemies.add(e);
        }
    }

    protected abstract Enemy createEnemy();
}
```

Each level is now a tiny class. The forest level returns a wolf. The ice level returns a yeti.

```java
public class ForestLevel extends Level {
    @Override protected Enemy createEnemy() { return new Wolf(); }
}

public class IceLevel extends Level {
    @Override protected Enemy createEnemy() { return new Yeti(); }
}
```

When lava arrives, it's one new class, and the level class doesn't change at all.

```java
public class LavaLevel extends Level {
    @Override protected Enemy createEnemy() { return new FireImp(); }
}
```

Ask an ice level to spawn a wave of five (`ice.spawnWave(5)`), and five yetis drop in, through the
same loop the forest uses. And a level that forgets to choose won't compile: a class that leaves an
abstract method unimplemented must itself be declared abstract. The parent made the slot, and the
compiler checks it's filled.

```mermaid {alt="Sequence: a caller asks IceLevel to spawnWave(5). The inherited spawnWave loop calls createEnemy() five times; IceLevel's override returns a new Yeti each time, which the loop places and keeps." caption="The parent's loop, the subclass's choice."}
sequenceDiagram
  participant G as Game
  participant L as IceLevel (spawnWave from Level)
  participant Y as Yeti
  G->>L: spawnWave(5)
  loop 5 times
    L->>L: createEnemy()
    L->>Y: new Yeti()
    L->>Y: placeAt(randomSpot())
  end
```

## Anatomy

The pattern has four roles. The level is the **creator**, the ice level a **concrete creator**.
`Enemy` is the **product**, and `Yeti` a **concrete product**.

```mermaid {alt="Class diagram of Factory Method: abstract Level (creator) with spawnWave() and abstract createEnemy(); IceLevel (concrete creator) overrides createEnemy(). Enemy interface (product) with placeAt; Yeti (concrete product) implements it; IceLevel creates Yeti." caption="Four roles."}
classDiagram
  class Level {
    <<abstract>>
    +spawnWave(int size)
    #createEnemy()* Enemy
  }
  class IceLevel {
    #createEnemy() Enemy
  }
  class Enemy {
    <<interface>>
    +placeAt(Spot spot)
  }
  Level <|-- IceLevel
  Enemy <|.. Yeti
  IceLevel ..> Yeti : creates
  Level --> Enemy : uses
```

A few design choices:

- **Abstract or a default.** The creation method can be abstract, so every level must choose. Or it
  can return a default, like a slime, that levels may override (shown below).
- **One step of a bigger routine.** Making enemies isn't the level's main job. The creation step is
  one step of a bigger routine, which makes `spawnWave` a template method (see
  [Template Method](/patterns/template-method-pattern/)).
- **Return the role.** The return type is the product interface, so the creator never depends on a
  concrete class.
- **Not always new.** The method doesn't have to make a new object each time. It can hand back one
  from a pool, or a cache.

The default version of the creation method:

```java
protected Enemy createEnemy() { return new Slime(); }   // default; levels may override
```

## You already use it: `Iterable.iterator()`

You've used this pattern every time you've written a for-each loop. `Iterable` declares one
method, `iterator`. The for-each loop (the language translates it into calls of `iterator()`,
`hasNext()` and `next()`), and the `forEach` method, are written once, against it.

```java
// java.lang.Iterable (simplified)
public interface Iterable<T> {
    Iterator<T> iterator();

    default void forEach(Consumer<? super T> action) {
        for (T t : this) action.accept(t);
    }
}
```

Each collection decides which iterator to make. `ArrayList` makes its own private class (`Itr`),
`ArrayDeque` another (`DeqIterator`), and `HashSet` hands out its map's. You never see those
classes. `Iterable` is the creator, and `iterator` is its factory method. Write your own collection,
give it an iterator, and every for-each loop in Java can walk through it.

## The mix-up: static factory methods

Now the biggest mix-up. `List.of`, and `Boolean.valueOf`, are often called factory methods.

```java
List<String> tags = List.of("forest", "night");
Boolean yes = Boolean.valueOf(true);
```

They are useful. Joshua Bloch recommends them in *Effective Java* (Item 1): they have names, they
don't have to make a new object every time, and they can return any subtype. But they're static. No
subclass can override them, so no subclass decides anything. Bloch says it plainly:

> "a static factory method is not the same as the Factory Method pattern from *Design Patterns*."

In the league, it's a costume shop where you order a mascot by name. One counter, and no clubs
involved.

> **Static can't be overridden, so it can't be this pattern.**

(Fowler's refactoring *Replace Constructor with Factory Function* produces this kind of static
creator, not the pattern.)

## The neighbours: simple factory, Abstract Factory, Builder

Three more neighbours get mixed up with it.

A **simple factory** is one method, with one switch that picks the class: the one switch that stays
in [Switch Statements](/code-smells/switch-statements/). It's fine, and often a first step. But
nothing is overridden. It's the league office's lookup sheet.

```java
static Enemy create(String kind) {
    return switch (kind) {
        case "wolf" -> new Wolf();
        case "yeti" -> new Yeti();
        default -> throw new IllegalArgumentException(kind);
    };
}
```

An **[Abstract Factory](/patterns/abstract-factory-pattern/)** is an object you pass in, and it makes a whole family that matches: the
enemy, the ground, and the music for one theme. It's a club's matching kit.

```java
public interface Theme {
    Enemy createEnemy();
    Tile createGround();
    Song createMusic();
}
```

And a **Builder** assembles one complex object, step by step, like a costume made piece by piece
(see [Builder](/patterns/builder-pattern/)).

| Look-alike | Who decides the class | How |
|---|---|---|
| static factory (`List.of`) | the class itself | a named static method |
| simple factory | one method | a switch on a value |
| **Factory Method** | **a subclass** | **overrides a creation step the parent calls** |
| Abstract Factory | an object you pass in | one method per product in a family |
| Builder | (one product) | steps that build one object |

Only the factory method has a subclass that overrides a creation step.

## When not to use it

When should you skip it?

- If there's only one kind of enemy, just call `new`.
- If the choice comes from data, like a config file (`"enemy": "yeti"`), a simple factory or a map
  reads better than a class per value.
- And if a subclass exists only to pick one class, pass the choice in instead. A supplier of enemies
  does the job, with `Yeti::new`:

```java
public class Level {
    private final Supplier<Enemy> spawner;

    public Level(Supplier<Enemy> spawner) { this.spawner = spawner; }

    // in spawnWave:  Enemy e = spawner.get();
}

Level ice = new Level(Yeti::new);
```

That's the Gang of Four's own advice: favour object composition over class inheritance. It's closer
to the [Strategy pattern](/patterns/strategy-pattern/). Factory Method shines when the
subclasses already exist for other reasons (each level has its own map, music and rules) and the
creation step is one more thing they specialise.

```mermaid {alt="Decision: only one kind of product? Just call new. Is the choice made from data at run time? Use a simple factory or a map. Do subclasses already exist for other reasons? Use Factory Method. Otherwise pass a Supplier in." caption="Subclass when the class already exists for other reasons."}
flowchart TD
  Q1{"only one kind?"} -->|yes| N["just call new"]
  Q1 -->|no| Q2{"chosen from data?"}
  Q2 -->|yes| SF["simple factory / map"]
  Q2 -->|no| Q3{"subclasses exist anyway?"}
  Q3 -->|yes| FM["Factory Method"]
  Q3 -->|no| SU["pass a Supplier"]
  class FM good
  class N,SF,SU muted
```

## Recap

- A `new`, welded into shared code, ties that code to one class.
- Move it behind a method the parent calls, and each subclass overrides. That's the factory method,
  and the JDK's `iterator()` is one.
- It's not a static factory; and when a subclass would exist only to choose, pass a supplier instead.

```mermaid {alt="Recap chain: find the welded new, replace it with a call, let each subclass override it, and pass a Supplier when subclassing is overkill." caption="The parent decides when. The subclass decides what."}
flowchart LR
  A["find the welded new"] --> B["call createEnemy()"] --> C["subclasses override"] --> D["only choosing? Supplier"]
  class B hl
  class C good
```

Checklist:

- Is there a `new` (or an `if` chain of them) in the middle of logic that should be shared?
- Do subclasses already exist that could each make the choice?
- Does the creation method return the product interface, not a concrete class?
- Is the creation method called by the parent's own routine (not by outside callers)?
- Would a `Supplier` or a simple factory be simpler here?

> **The parent decides when. The subclass decides what.**

Related lessons: [Template Method](/patterns/template-method-pattern/),
[Builder](/patterns/builder-pattern/), [Strategy](/patterns/strategy-pattern/),
[Polymorphism](/fundamentals/polymorphism/), [Switch Statements](/code-smells/switch-statements/).

## Further reading

- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, *Design Patterns* (1994): Factory Method, p. 107.
- Joshua Bloch, *Effective Java*, Item 1: "Consider static factory methods instead of constructors".
- refactoring.guru: [Factory Method](https://refactoring.guru/design-patterns/factory-method) and
  [Factory Comparison](https://refactoring.guru/design-patterns/factory-comparison).
- [`java.lang.Iterable`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Iterable.html) javadoc.
