LLD

Creational Patterns

Prototype pattern

When objects are costly to set up and many of them start out the same, set one up and copy it. We build an enemy spawner for a tower-defence game twice, once from scratch every time and once by copying templates.

A tower-defence game sends enemies down a lane in waves. A wave might be forty goblins, ten armoured goblins and a boss. Every goblin starts the same: the same picture, 50 health, the same speed. Then each one goes its own way. One gets hit by an arrow, another is set on fire, a third reaches the gate.

Building each enemy from nothing is wasteful. The picture, called a sprite, has to be read from disk and decoded, and that is slow. The numbers come from a level file that has to be read and checked. Doing all of that forty times for forty identical goblins makes no sense.

The Prototype pattern sets up one object, the prototype, and makes every new object by copying it. In this article we build an enemy spawner twice. The first version builds every enemy from scratch. The second keeps one template per kind of enemy and hands out copies. Then we look at how deep a copy has to go, why Java's own clone() is a poor fit, and how Prototype compares with Factory and Builder.

All the code is Java. Every snippet without a Sketch label is cut from a project that compiles: the first-version snippets from the build-from-scratch version, the rest from the finished design. Both programs run, and the outputs shown are what they print.

The spawner we are building

The game asks for an enemy by name, such as "goblin" or "boss". The spawner must:

  1. Hand out a new enemy for each request, at full health, at the start of the lane, with no status effects.
  2. Keep every enemy separate. Damage, fire or movement on one enemy never shows on another, or on the next one spawned.
  3. Read each sprite once. A wave of forty goblins reads goblin.png once, not forty times.
  4. Take new kinds of enemy from the level file, without a code change. A "fast goblin" is a goblin with more speed.
  5. Refuse mistakes clearly: an unknown name, a name defined twice, a broken line in the level file.
  6. Allow spawning while a level loads on another thread.
Templates in, copies out
The level file is read once (1), and each sprite is loaded once (2). The registry keeps one template per kind: goblin, armoured goblin and boss (3). Each request copies a template (4). The three goblin copies have their own health, position and effects, and all of them point at the one goblin sprite, as the templates do (5).The level file is read once (1), and each sprite is loaded once (2). The registry keeps one template per kind: goblin, armoured goblin and boss (3). Each request copies a template (4). The three goblin copies have their own health, position and effects, and all of them point at the one goblin sprite, as the templates do (5).
The registry keeps one template per kind and hands out copies. The level file is read once (1), and each sprite is loaded once (2). The registry keeps one template per kind: goblin, armoured goblin and boss (3). Each request copies a template (4). The three goblin copies have their own health, position and effects, and all of them point at the one goblin sprite, as the templates do (5).

This figure is the one to draw first in an interview. It separates the few templates, which never change, from the many copies, which change all the time. It also shows the one thing the copies share: the sprite.

The first version: build every enemy from scratch

The obvious version is a factory with one case per kind of enemy:

EnemyFactory.javalines 8–15 of 16
    public Enemy create(String kind) {        return switch (kind) {            case "goblin" -> new Enemy("goblin", sprites.load("goblin.png"), 50, 0, 4, 5);            case "armoured-goblin" -> new Enemy("armoured-goblin", sprites.load("goblin.png"), 120, 4, 2, 9);            case "boss" -> new Enemy("boss", sprites.load("boss.png"), 900, 6, 1, 100);            default -> throw new IllegalArgumentException("No enemy called " + kind);        };    }

This code works, and for a game with three kinds of enemy and small waves it is fine. The trouble shows when the waves grow and the kinds keep changing.

Every enemy reloads its sprite. sprites.load("goblin.png") runs on every call, so a wave of eight enemies reads a sprite eight times.

The numbers live in the code. A designer who wants a fast goblin needs a new case, a new build and a new release.

The quick fix for the first problem is to build each kind once and hand out that object:

SharedEnemies.javalines 4–16 of 16
// The quick fix for slow spawning: build each kind once and hand out that object.public class SharedEnemies {    private final EnemyFactory factory;    private final Map<String, Enemy> built = new HashMap<>();     public SharedEnemies(EnemyFactory factory) {        this.factory = factory;    }     public Enemy spawn(String kind) {        return built.computeIfAbsent(kind, factory::create);    }}

Now every goblin is the same object. When an arrow hits one goblin, every goblin on the screen loses health. The first version's program shows all three problems:

$ java Main
1. A wave of 8 enemies loaded a sprite 8 times
2. No enemy called fast-goblin: a new kind needs a new case and a new release
3. Shared objects: hit the first goblin, and the second shows 20/50
Two ways to get it wrong
On the left, the factory loads goblin.png again for each of the five goblins, eight loads for a wave of eight. On the right, the quick fix hands the same goblin object to every caller. One hit of 30 shows as 20/50 on every goblin, in red.On the left, the factory loads goblin.png again for each of the five goblins, eight loads for a wave of eight. On the right, the quick fix hands the same goblin object to every caller. One hit of 30 shows as 20/50 on every goblin, in red.
Building from scratch is slow. Sharing one object is wrong. On the left, the factory loads goblin.png again for each of the five goblins, eight loads for a wave of eight. On the right, the quick fix hands the same goblin object to every caller. One hit of 30 shows as 20/50 on every goblin, in red.

We need something in between: each enemy should be its own object, without paying for the setup again.

The idea

The pattern works like this:

  • For each kind of enemy, the game sets up one fully built object, a template, and keeps it in a registry under its name.
  • An object that can copy itself is called a prototype. Here every Enemy can, through a copy() method.
  • To spawn an enemy, the registry finds the template and returns a copy of it.
  • A copy shares only what can never change, such as the sprite. Everything that can change, such as health and effects, belongs to the copy alone.

The costly work, reading the level file and loading sprites, happens once per kind. Each spawn after that is a copy of a few fields.

Building it, step by step

Step 1: a copy that keeps everything

Enemy gets a private constructor that takes another enemy and copies its fields, and a public copy() that calls it:

enemy/Enemy.javalines 13–50 of 165
    private final String kind;    private final Sprite sprite;    private final int maxHealth;    private final int armour;    private final int speed;    private final int reward;     private int health;    private Position position;    private final List<StatusEffect> effects;     public Enemy(String kind, Sprite sprite, int maxHealth, int armour, int speed, int reward) {        this.kind = checkKind(kind);        this.sprite = Objects.requireNonNull(sprite, "sprite");        this.maxHealth = checkAtLeast(maxHealth, 1, "maxHealth");        this.armour = checkAtLeast(armour, 0, "armour");        this.speed = checkAtLeast(speed, 1, "speed");        this.reward = checkAtLeast(reward, 0, "reward");        this.health = maxHealth;        this.position = Position.START;        this.effects = new ArrayList<>();    }     private Enemy(Enemy source) {        this.kind = source.kind;        this.sprite = source.sprite; // shared on purpose: a Sprite never changes        this.maxHealth = source.maxHealth;        this.armour = source.armour;        this.speed = source.speed;        this.reward = source.reward;        this.health = source.health;        this.position = source.position;        this.effects = new ArrayList<>(source.effects);    }     public Enemy copy() {        return new Enemy(this);    }

Most fields are copied as they are. Two lines need a closer look.

Line 38 copies the sprite reference, so the copy and the original point at the same Sprite object. That is safe because Sprite is a record of a file name and a frame count, and nothing can change it. A real sprite would also hold its pixels in an array. That class must keep the array private and never hand it out, because a record does not stop anyone changing the contents of an array it holds. Sharing it is the point: the sprite is the costly part.

Line 45 makes a new list holding the same effects. The original's list and the copy's list are now two objects, so adding a burn to one does not add it to the other. Each StatusEffect inside is a record that never changes, so copying the list is enough. If a StatusEffect could change, each one would need copying too.

position is a Position record, which never changes, so line 44 can share it. health is an int, which is copied by value.

Enemy is final, and that is part of the design. If a FlyingGoblin extended Enemy, calling copy() on one would run Enemy's copy constructor and return a plain Enemy, losing the subclass and its extra fields. A class hierarchy that uses Prototype needs every subclass to override copy() and call its own copy constructor, and a forgotten override is another silent bug. Here every kind of enemy differs only in its numbers, so one final class is enough, and the kinds live in data.

How deep the copy goes
On the left, a shallow copy shares the effects list. Setting the copy on fire puts BURNING into the template's list too, in red. On the right, our copy makes its own effects list and still shares the sprite, which nothing can change.On the left, a shallow copy shares the effects list. Setting the copy on fire puts BURNING into the template's list too, in red. On the right, our copy makes its own effects list and still shares the sprite, which nothing can change.
Share what never changes. Copy what can change. On the left, a shallow copy shares the effects list. Setting the copy on fire puts BURNING into the template's list too, in red. On the right, our copy makes its own effects list and still shares the sprite, which nothing can change.
Decision

Java's clone() or our own copy()?

Implement Cloneable and override clone()

Java has a built-in way to copy objects, and it has two real strengths. super.clone() called on a subclass returns that subclass, which keeps the subclass, though a subclass with its own list still has to override clone() to copy it. It also copies every field, so no field can be forgotten. It has two problems here. It is shallow, so the effects list is shared unless we replace it, and we cannot replace it, because effects is final and a final field cannot be assigned after construction. And Object.clone() throws the checked CloneNotSupportedException, so the overriding method must catch it even though it never happens here.

A private copy constructor and a public copy()Our pick

The copy constructor is ordinary Java. Every final field must be set, or the class does not compile. The effects list can stay final, because the constructor creates it. The copy runs no checks, and needs none, because its source was checked when it was built. The cost is the two strengths we give up: every new field needs a line here, and a forgotten line for a field that is not final, such as health, still compiles. Enemy is final, so the subclass problem does not arise.

The rejected option, written out, shows where it breaks:

Sketchnot part of the final code
class Enemy implements Cloneable {    private final List<StatusEffect> effects = new ArrayList<>();     @Override    public Enemy clone() {        try {            Enemy copy = (Enemy) super.clone();            // copy.effects = new ArrayList<>(effects);   does not compile: effects is final            return copy;        } catch (CloneNotSupportedException e) {            throw new AssertionError(e);        }    }}

Step 2: a registry of templates

EnemyTemplates keeps one template per name in a map and hands out copies:

spawn/EnemyTemplates.javalines 16–51 of 75
public final class EnemyTemplates {    // Readers take the current map; a load swaps in a new map with all its kinds at once.    private final AtomicReference<Map<String, Enemy>> templates = new AtomicReference<>(Map.of());     public void register(Enemy template) {        registerAll(List.of(template));    }     public void registerAll(List<Enemy> newTemplates) {        Objects.requireNonNull(newTemplates, "newTemplates");        List<Enemy> stored = new ArrayList<>();        for (Enemy template : newTemplates) {            Objects.requireNonNull(template, "template");            if (!template.isFresh()) {                throw new IllegalArgumentException("A template must be at full health, at the start, with no effects: " + template);            }            stored.add(template.copy());        }        publish(stored);    }     public Enemy spawn(String kind) {        Objects.requireNonNull(kind, "kind");        Map<String, Enemy> current = templates.get();        Enemy template = current.get(kind);        if (template == null) {            throw new UnknownEnemyException(kind, new TreeSet<>(current.keySet()));        }        return template.copy();    }     public Optional<Enemy> find(String kind) {        Objects.requireNonNull(kind, "kind");        Enemy template = templates.get().get(kind);        return template == null ? Optional.empty() : Optional.of(template.copy());    }

Three lines do the copying. Line 44 is the obvious one: spawn returns template.copy(), never the template. Line 50 does the same for find, which the loader uses to look up a base kind. Line 32 is easy to miss: registerAll stores a copy of what it is given. Without it, the code that registered a goblin could keep its reference and damage the template later.

Decision

What leaves the registry, and what goes in?

Store what we are given, hand out the template

This is the fastest version, and it is exactly the shared-object bug from the first version. One hit on a goblin changes every goblin that comes after it.

Copy on the way in and on the way outOur pick

No code outside the registry ever holds a template, so nothing can change one after it is registered. The cost is one extra copy when a template is registered, which happens once per kind.

Step 3: refuse what does not fit

registerAll refuses two things. Line 29 refuses a template that is not fresh: one that is damaged, has moved or carries an effect. Every spawn copies the template, so a damaged template would mean every enemy of that kind starts damaged. The second refusal, a name that is already taken, comes in Step 4, where the new templates are added.

Decision

A second template with the same name

Replace the first one

Reloading a level could then update its enemies. But a typo that names two different enemies "goblin" would silently keep only one of them, and which one depends on the order of the lines.

Refuse itOur pick

The clash is found before anything is published, so the first goblin stays as it was. Updating a kind is then a deliberate act, done with a new registry.

spawn with an unknown name throws UnknownEnemyException, and its message lists the names that do exist, or says that none are registered yet. That message is meant for the person writing the level file, so they can see the typo at once. A null name, or a bad number passed in code, is a programmer's mistake and fails straight away with NullPointerException or IllegalArgumentException.

Step 4: new kinds from the level file

The level file describes each kind on one line. A kind either names its own sprite or starts from another kind:

goblin: sprite goblin.png, health 50, armour 0, speed 4, reward 5armoured-goblin: like goblin, health 120, armour 4, speed 2, reward 9boss: sprite boss.png, health 900, armour 6, speed 1, reward 100

A "like" line is the pattern again. It copies an existing template and changes some numbers. variant keeps the sprite and takes the new numbers, and the new enemy starts fresh:

enemy/Enemy.javalines 52–54 of 165
    public Enemy variant(String newKind, int newMaxHealth, int newArmour, int newSpeed, int newReward) {        return new Enemy(newKind, sprite, newMaxHealth, newArmour, newSpeed, newReward);    }

TemplateLoader reads the lines and parses each one. A sprite named on a "sprite" line goes through the sprite method, which keeps every sprite it has loaded in a map, so each file is read once per loader, however many lines use it. That map is a plain HashMap, so a loader belongs to one thread, and a level that loads on two threads uses two loaders:

spawn/TemplateLoader.javalines 66–90 of 133
        if (first.startsWith(SPRITE)) {            Sprite sprite = sprite(first.substring(SPRITE.length()).strip());            return new Enemy(kind, sprite, required(settings, "health"), required(settings, "armour"),                    required(settings, "speed"), required(settings, "reward"));        }        if (first.startsWith(LIKE)) {            Enemy base = base(first.substring(LIKE.length()).strip(), parsed, templates);            return base.variant(kind, settings.getOrDefault("health", base.maxHealth()),                    settings.getOrDefault("armour", base.armour()), settings.getOrDefault("speed", base.speed()),                    settings.getOrDefault("reward", base.reward()));        }        throw new IllegalArgumentException("start with 'sprite file' or 'like other'");    }     private Sprite sprite(String file) {        Sprite sprite = loaded.get(file);        if (sprite == null) {            sprite = sprites.load(file);            if (sprite == null) {                throw new IllegalStateException("the sprite loader returned nothing for " + file);            }            loaded.put(file, sprite);        }        return sprite;    }

The loader registers a whole file or none of it:

spawn/TemplateLoader.javalines 27–55 of 133
    // Registers every template in the lines, or none of them.    public void loadInto(EnemyTemplates templates, List<String> lines) {        Objects.requireNonNull(templates, "templates");        Objects.requireNonNull(lines, "lines");        Map<String, Enemy> parsed = new LinkedHashMap<>();        Map<String, Integer> lineOf = new HashMap<>();        for (int i = 0; i < lines.size(); i++) {            int number = i + 1;            String line = Objects.requireNonNull(lines.get(i), "line " + number).strip();            if (line.isEmpty() || line.startsWith("#")) {                continue;            }            try {                Enemy template = parse(line, parsed, templates);                if (parsed.containsKey(template.kind()) || templates.has(template.kind())) {                    throw new IllegalArgumentException("'" + template.kind() + "' is defined twice");                }                parsed.put(template.kind(), template);                lineOf.put(template.kind(), number);            } catch (RuntimeException e) {                throw new IllegalArgumentException("line " + number + ": " + e.getMessage(), e);            }        }        try {            templates.registerAll(new ArrayList<>(parsed.values()));        } catch (DuplicateTemplateException e) {            throw new IllegalArgumentException("line " + lineOf.get(e.kind()) + ": " + e.getMessage(), e);        }    }

The loop parses every line and checks every name before anything is registered. A broken line 7 therefore leaves lines 1 to 6 unregistered too. Any failure on a line, including a sprite that cannot load, is passed on with the line number in front. Then registerAll adds the whole file in one step, through publish:

spawn/EnemyTemplates.javalines 61–74 of 75
    private void publish(List<Enemy> stored) {        while (true) {            Map<String, Enemy> current = templates.get();            Map<String, Enemy> next = new HashMap<>(current);            for (Enemy template : stored) {                if (next.putIfAbsent(template.kind(), template) != null) {                    throw new DuplicateTemplateException(template.kind());                }            }            if (templates.compareAndSet(current, Map.copyOf(next))) {                return;            }        }    }

publish builds a new map from the current one plus every new template, and swaps it in with compareAndSet. Other threads read either the old map or the new one, never a map with half a file in it. Every load copies the whole map, and a lost compareAndSet copies it again. That is cheap here because loads are rare and kinds are few, and code with many templates to add should pass them to registerAll together rather than one at a time. If another thread swapped in its own map first, compareAndSet fails and the loop starts again from the newer map, so neither load is lost. A name that is already taken throws DuplicateTemplateException before anything is swapped in, and the loader reports it with that name's line number.

Every error message from the loader starts with its line number and uses the file's own words, such as line 3: health must be at least 1, got 0, because it is read by the person editing the level file.

Step 5: spawning while a level loads

A level can load its enemy kinds on a loading thread while the game thread spawns enemies. The registry is safe for that without a lock. templates is an AtomicReference holding a map that is never changed after it is built. A reader takes the current map and looks up its template there, and a load swaps in a new map. A template is never changed after it is stored either. The only thing anyone does to it is call copy(), which only reads its fields, and many threads can read at once.

This safety rests on one rule: nothing changes a template in place. A feature like "every goblin gets 10 more health tonight" must not edit the stored goblin, because a thread copying it at that moment could see half of the change. The feature builds a new registry with the stronger goblin instead, and the game switches to it through a volatile field or an AtomicReference that holds the current registry.

The project includes demo/RaceCheck.java. Four threads spawn 2,500 goblins each and damage each one, while a fifth thread adds 100 new kinds:

$ java demo.RaceCheck
spawned 10000 goblins on 4 threads while 100 templates were added: 0 started damaged, 101 templates at the end, template health 50

Every goblin started at full health, every new kind was added, and the goblin template still has 50 health at the end.

The finished design

The finished design
EnemyTemplates owns one Enemy template per kind, in a map held by an AtomicReference, and returns copies from spawn and find. Enemy holds a Sprite, a Position and a list of StatusEffect records, and copy() shares the first two and copies the list. TemplateLoader reads the level file, loads each sprite once through the SpriteLoader interface, and registers the whole file with registerAll. An unknown name throws UnknownEnemyException, and a name already taken throws DuplicateTemplateException.EnemyTemplates owns one Enemy template per kind, in a map held by an AtomicReference, and returns copies from spawn and find. Enemy holds a Sprite, a Position and a list of StatusEffect records, and copy() shares the first two and copies the list. TemplateLoader reads the level file, loads each sprite once through the SpriteLoader interface, and registers the whole file with registerAll. An unknown name throws UnknownEnemyException, and a name already taken throws DuplicateTemplateException.
The registry owns templates. Every spawn is a copy. EnemyTemplates owns one Enemy template per kind, in a map held by an AtomicReference, and returns copies from spawn and find. Enemy holds a Sprite, a Position and a list of StatusEffect records, and copy() shares the first two and copies the list. TemplateLoader reads the level file, loads each sprite once through the SpriteLoader interface, and registers the whole file with registerAll. An unknown name throws UnknownEnemyException, and a name already taken throws DuplicateTemplateException.

Here is one spawn, traced through the objects:

One spawn, traced
The game asks for a goblin (1). EnemyTemplates finds the goblin template in its map (2) and calls copy() on it (3). The copy constructor shares the sprite and makes a new effects list (4). The new enemy goes back to the game (5), which hits it for 30 (6). The template is untouched.The game asks for a goblin (1). EnemyTemplates finds the goblin template in its map (2) and calls copy() on it (3). The copy constructor shares the sprite and makes a new effects list (4). The new enemy goes back to the game (5), which hits it for 30 (6). The template is untouched.
The registry looks up the template and copies it. The game asks for a goblin (1). EnemyTemplates finds the goblin template in its map (2) and calls copy() on it (3). The copy constructor shares the sprite and makes a new effects list (4). The new enemy goes back to the game (5), which hits it for 30 (6). The template is untouched.

The whole project is below. Click any class name in the code to open that class.

spawnEnemyTemplates.java
package spawn; import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional;import java.util.SortedSet;import java.util.TreeSet;import java.util.concurrent.atomic.AtomicReference; import enemy.Enemy; public final class EnemyTemplates {    // Readers take the current map; a load swaps in a new map with all its kinds at once.    private final AtomicReference<Map<String, Enemy>> templates = new AtomicReference<>(Map.of());     public void register(Enemy template) {        registerAll(List.of(template));    }     public void registerAll(List<Enemy> newTemplates) {        Objects.requireNonNull(newTemplates, "newTemplates");        List<Enemy> stored = new ArrayList<>();        for (Enemy template : newTemplates) {            Objects.requireNonNull(template, "template");            if (!template.isFresh()) {                throw new IllegalArgumentException("A template must be at full health, at the start, with no effects: " + template);            }            stored.add(template.copy());        }        publish(stored);    }     public Enemy spawn(String kind) {        Objects.requireNonNull(kind, "kind");        Map<String, Enemy> current = templates.get();        Enemy template = current.get(kind);        if (template == null) {            throw new UnknownEnemyException(kind, new TreeSet<>(current.keySet()));        }        return template.copy();    }     public Optional<Enemy> find(String kind) {        Objects.requireNonNull(kind, "kind");        Enemy template = templates.get().get(kind);        return template == null ? Optional.empty() : Optional.of(template.copy());    }     public boolean has(String kind) {        return templates.get().containsKey(kind);    }     public SortedSet<String> kinds() {        return Collections.unmodifiableSortedSet(new TreeSet<>(templates.get().keySet()));    }     private void publish(List<Enemy> stored) {        while (true) {            Map<String, Enemy> current = templates.get();            Map<String, Enemy> next = new HashMap<>(current);            for (Enemy template : stored) {                if (next.putIfAbsent(template.kind(), template) != null) {                    throw new DuplicateTemplateException(template.kind());                }            }            if (templates.compareAndSet(current, Map.copyOf(next))) {                return;            }        }    }}
Click a class name in the code to open its fileJava · 75 lines · 606 in the project

The demo in demo/Main.java loads a level, spawns a wave and plays with it:

$ java demo.Main
1. Templates [armoured-goblin, boss, goblin], sprite loads so far: 2
2. Spawned 8 enemies, sprite loads still: 2
3. First goblin:  goblin 20/50 at lane 1 step 3 [BURNING for 2 ticks]
   Second goblin: goblin 50/50 at lane 0 step 0
   New goblin:    goblin 50/50 at lane 0 step 0
   Both goblins share one sprite object: true
4. After two ticks of burning: goblin 14/50 at lane 1 step 3
5. A hit of 10 on an armoured goblin deals 6: armoured-goblin 114/120 at lane 0 step 0
6. No enemy template named 'dragon'. Known: armoured-goblin, boss, goblin
7. Added at runtime: fast-goblin 50/50 at lane 0 step 0, speed 7, sprite goblin.png, sprite loads: 2
8. A template named 'goblin' is already registered

Line 2 is requirement 3: eight enemies, still two sprite loads. Line 3 is requirement 2: the first goblin is damaged, burning and moved, while the second goblin and a newly spawned one are untouched, and both goblins share one sprite. Line 5 shows armour 4 turning a hit of 10 into 6. Line 7 adds a fast goblin from one new line, with no new sprite load. Lines 6 and 8 are the two refusals.

What it costs

The pattern makes one kind of change cheap and another more expensive.

A new kind of enemy is cheap. A fast goblin is one line in the level file. No class changes, and the game does not need a new release.

A new field is more expensive. A "flying" flag on Enemy, which an arrow can knock off, needs a field, a constructor parameter, a line in the copy constructor and a parameter on variant. isFresh must check it too, or a knocked-down flyer could become a template. The loader needs a new setting and a "like" default for it. Forgetting the copy-constructor line compiles, because the field is not final, and every copy then starts on the ground.

Where a change lands
On the left, a fast goblin is one new line in the level file, tagged new. Enemy, EnemyTemplates and TemplateLoader do not change. On the right, a new flying field changes five places in Enemy and one in TemplateLoader, outlined in amber. A goblin can be knocked out of the air, so flying is not final, and the compiler cannot check the copy-constructor line.On the left, a fast goblin is one new line in the level file, tagged new. Enemy, EnemyTemplates and TemplateLoader do not change. On the right, a new flying field changes five places in Enemy and one in TemplateLoader, outlined in amber. A goblin can be knocked out of the air, so flying is not final, and the compiler cannot check the copy-constructor line.
A new kind is one line of data. A new field touches the copy. On the left, a fast goblin is one new line in the level file, tagged new. Enemy, EnemyTemplates and TemplateLoader do not change. On the right, a new flying field changes five places in Enemy and one in TemplateLoader, outlined in amber. A goblin can be knocked out of the air, so flying is not final, and the compiler cannot check the copy-constructor line.

There are smaller costs too. Readers have to know that spawn copies, and that copy() shares the sprite. A copy constructor that forgets a field is a quiet bug.

When the pattern is too much

If an object is cheap to build and there are only a few kinds, calling the constructor is clearer than keeping templates:

Sketchnot part of the final code
Enemy goblin = new Enemy("goblin", goblinSprite, 50, 0, 4, 5);

The pattern also adds little when every copy changes most of its fields straight away. Copying a template and then overwriting nine of its ten fields does the same work as building from scratch, and it hides which values came from where.

The pattern earns its place when the setup is costly and many objects start the same, or when the kinds come from data rather than code. Our spawner has both.

Prototype, Factory or Builder?

All three hand out new objects, so they are easy to confuse.

PrototypeFactoryBuilder
How the new object is madeCopy a configured objectPick a class from a value and call its constructorSet values one at a time, then build
Where the kinds come fromData, at runtimeCode, one class or case per kindCode, one product class
Pays off whenSetup is costly and many objects start the sameCallers should not know the classesAn object has many optional values
ExampleA goblin copied from its templateAn exporter picked by format nameA flight search with filters

The Builder pattern page agrees: Prototype pays off when creating an object from scratch is expensive. For its flight search that page chose toBuilder(), because "a search is cheap to create, and we want to change some values on the way". The Memento pattern page draws the other line. A prototype is a live copy made to be used as a new object. A memento is a sealed copy made to be given back to the object it came from.

The patterns also combine. Our registry is a factory that makes its products by copying, and a template could itself be built with a builder before it is registered.

A short way to say it: a factory builds from a class, a builder builds from values, and a prototype builds from an example.

In an interview

The Prototype pattern appears inside low-level design questions about games, documents built from templates, and any system where an administrator defines new kinds of thing without a release. Spawning enemies, copying a slide layout and creating a new account from a plan are all the same shape.

A good order for presenting it:

  1. Draw templates and copies first, with the one shared object between them.
  2. Say which fields are shared and which are copied, and why: shared means it never changes.
  3. Then write copy() and the registry, and say that the registry copies on the way in and on the way out.

One follow-up tests the same idea. What if a template holds a reference to something that does change, such as a list of targets shared by a whole wave? Then the copy must decide again. Either each copy gets its own list, or every copy shares the one list on purpose, and the code says which in a comment on that line of the copy constructor.

Common mistakes:

  • Handing out the template itself. Every enemy then shares one health bar.
  • A shallow copy of a list. Burning one goblin sets every goblin on fire.
  • A deep copy of everything. Copying the sprite for every goblin brings back the cost the pattern was meant to remove.
  • Forgetting a field in the copy constructor. Fields that are not final compile without it and quietly start at their default.
  • Templates that can change. If code outside the registry can reach a template, one bug changes every future enemy of that kind.

Summary

  • Use Prototype when setup is costly and many objects start the same, or when the kinds come from data.
  • Give each class a copy constructor and a copy() method rather than Cloneable.
  • Share fields that never change. Copy fields that can, such as lists.
  • Keep templates in a registry that copies on the way in and on the way out, and refuses duplicates and unknown names.
  • A new kind is then a line of data. A new field touches every place that copies or reads enemy data: the copy constructor, variant, isFresh and the loader.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.