November 25, 20269 minutes
Fifty 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.
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.
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.
new itHere’s the forest version. The level spawns a wave, and for each enemy it makes a new wolf, places it, and keeps it.
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.
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.)
Then the ice level arrives, and the new line grows a branch on the theme. Then lava arrives, and
it grows another.
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.
This is the creation-side cousin of Switch Statements: a choice on a kind, repeated and growing.
new behind a methodThe 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.
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.
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.
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.
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.
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.
A few design choices:
spawnWave a template method (see
Template Method).The default version of the creation method:
protected Enemy createEnemy() { return new Slime(); } // default; levels may overrideIterable.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.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.
Now the biggest mix-up. List.of, and Boolean.valueOf, are often called factory methods.
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.)
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. It’s fine, and often a first step. But nothing is overridden. It’s the league office’s lookup sheet.
static Enemy create(String kind) {
return switch (kind) {
case "wolf" -> new Wolf();
case "yeti" -> new Yeti();
default -> throw new IllegalArgumentException(kind);
};
}An Abstract Factory 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.
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).
| 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 should you skip it?
new."enemy": "yeti"), a simple factory or a map
reads better than a class per value.Yeti::new: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. 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.
new, welded into shared code, ties that code to one class.iterator() is one.Checklist:
new (or an if chain of them) in the middle of logic that should be shared?Supplier or a simple factory be simpler here?The parent decides when. The subclass decides what.
Related lessons: Template Method, Builder, Strategy, Polymorphism, Switch Statements.
java.lang.Iterable javadoc.