LOW-LEVEL DESIGN · CREATIONAL PATTERNS · CREATIONAL · 26 OF 48

Prototype Pattern in Java: Shallow vs Deep Copy, Clone vs Copy

The Prototype pattern with game levels: load and configure a level once, then create variants by copying it. Covers the shallow copy bug where copies share mutable parts, deep copies with a copy constructor, why clone() and Cloneable are awkward, a registry of named prototypes, and how it compares with factories and builders.

Reported atHCLTech
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 15

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 155 lines, with a small main() demo. Save it as GameLevelPrototypeDemo.java, then run javac GameLevelPrototypeDemo.java && java GameLevelPrototypeDemo.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** Prototype with game levels: load once, then create variants by deep copying. */
public class GameLevelPrototypeDemo {

    /** A mutable part of a level. Has its own copy constructor. */
    static final class EnemySpawn {
        final String type;
        int x;
        int y;
        int health;

        EnemySpawn(String type, int x, int y, int health) {
            this.type = type;
            this.x = x;
            this.y = y;
            this.health = health;
        }

        EnemySpawn(EnemySpawn other) {           // copy constructor
            this(other.type, other.x, other.y, other.health);
        }

        @Override
        public String toString() {
            return type + "(" + health + "hp)";
        }
    }

    // ---------- the trap: clone() gives a shallow copy ----------
    static final class ShallowLevel implements Cloneable {
        String name;
        List<EnemySpawn> spawns = new ArrayList<>();

        @Override
        public ShallowLevel clone() {
            try {
                return (ShallowLevel) super.clone();   // copies the reference to spawns, not the list
            } catch (CloneNotSupportedException e) {
                throw new AssertionError(e);
            }
        }
    }

    // ---------- the prototype: a deep copy through a copy constructor ----------
    static final class GameLevel {
        private String name;
        private final String theme;                  // immutable: safe to share
        private final List<EnemySpawn> spawns;       // mutable parts: must be copied
        private final Map<String, Integer> loot;     // String and Integer are immutable

        GameLevel(String name, String theme) {
            this.name = name;
            this.theme = theme;
            this.spawns = new ArrayList<>();
            this.loot = new HashMap<>();
        }

        private GameLevel(GameLevel other) {
            this.name = other.name;
            this.theme = other.theme;
            this.spawns = new ArrayList<>();
            for (EnemySpawn s : other.spawns) {
                this.spawns.add(new EnemySpawn(s)); // a new object for every mutable element
            }
            this.loot = new HashMap<>(other.loot);
        }

        GameLevel copy() {
            return new GameLevel(this);
        }

        GameLevel rename(String newName) {
            this.name = newName;
            return this;
        }

        GameLevel addSpawn(EnemySpawn spawn) {
            spawns.add(spawn);
            return this;
        }

        GameLevel addLoot(String item, int count) {
            loot.put(item, count);
            return this;
        }

        void scaleHealth(int factor) {
            for (EnemySpawn s : spawns) {
                s.health *= factor;
            }
        }

        @Override
        public String toString() {
            return name + " [" + theme + "] " + spawns + " loot=" + loot;
        }
    }

    /** Pretends to read map files from disk: slow, so we want to do it once. */
    static final class LevelLoader {
        static int loads = 0;

        static GameLevel load(String key) {
            loads++;
            return new GameLevel(key, "sand dunes")
                    .addSpawn(new EnemySpawn("scorpion", 4, 9, 40))
                    .addSpawn(new EnemySpawn("vulture", 12, 2, 25))
                    .addLoot("water", 3);
        }
    }

    /** Keeps configured masters by name and only ever hands out copies. */
    static final class LevelRegistry {
        private final Map<String, GameLevel> masters = new HashMap<>();

        void register(String key, GameLevel master) {
            masters.put(key, master.copy());         // the caller cannot change our master later
        }

        GameLevel create(String key) {
            GameLevel master = masters.get(key);
            if (master == null) {
                throw new IllegalArgumentException("no prototype named " + key);
            }
            return master.copy();
        }
    }

    public static void main(String[] args) {
        // 1. Shallow copy: both levels share one spawn list.
        ShallowLevel original = new ShallowLevel();
        original.name = "desert";
        original.spawns.add(new EnemySpawn("scorpion", 4, 9, 40));
        ShallowLevel hardCopy = original.clone();
        hardCopy.spawns.get(0).health = 999;
        System.out.println("Shallow: original now " + original.spawns + "   <- changed by the copy!");

        // 2. Deep copy through a registry: load once, copy many times.
        LevelRegistry registry = new LevelRegistry();
        registry.register("desert", LevelLoader.load("desert"));

        GameLevel hard = registry.create("desert").rename("desert-hard");
        hard.scaleHealth(2);
        hard.addLoot("gold", 10);
        GameLevel night = registry.create("desert").rename("desert-night");

        System.out.println("Deep:    " + hard);
        System.out.println("Deep:    " + night + "   <- untouched by the hard copy");
        System.out.println("Slow loads from disk: " + LevelLoader.loads);
    }
}

Notes

The problem

Here is the naive way. To make three variants, the level editor asks the loader for the desert level three times, and tweaks each one. Every call reads the map files again, even though the result is identical before the tweaks. Any setup the editor does after loading is repeated in each place. And if the loaded level came from a class the editor does not even know, it cannot simply call new on it.

From scratch every time
GameLevel easy = loader.load("desert");
easy.setEnemyHealthScale(0.5);
GameLevel hard = loader.load("desert");
hard.setEnemyHealthScale(2.0);
GameLevel night = loader.load("desert");
night.setLighting("night");

// three slow loads of the same file
// setup steps copied in many places

The idea

The idea in plain words. Keep one fully set up object, called the prototype. When you need another like it, ask the prototype to copy itself, then change only what is different. The object makes the copy because it knows its own fields best, including private ones and which parts need copying deeply. The caller does not need to know the concrete class or how it was built.

Prototype in plain words
  • keep one fully set-up object
  • to make another, ask it for
  • a copy of itself, then
  • change only what differs
  • the object knows its own
  • fields, so it knows how to
  • copy them correctly

The participants

The participants. Game level is the prototype class, with a copy method. Desert master is one configured instance of it, loaded once. Enemy spawn is a mutable part that each level owns: an enemy type, a position and health. Level registry keeps prototypes by name. The level editor, the client, asks the registry for a fresh desert level and gets a copy, never the master itself.

Shallow copy

First, the trap. Object dot clone makes a shallow copy. It copies each field as it is. For a number that is fine, but for the spawn list it copies only the reference. Now the original and the copy point to the same list and the same enemy objects. Set the first enemy's health to nine hundred and ninety nine in the hard copy, and the scorpion in the original level has nine hundred and ninety nine too.

ShallowLevel.clone()
class ShallowLevel implements Cloneable {
  List<EnemySpawn> spawns;
  public ShallowLevel clone() {
    return (ShallowLevel) super.clone();
  }
}

copy.spawns.get(0).health = 999;
// the ORIGINAL scorpion now has 999

Why it hurts

This kind of bug is nasty, because the change happens in one place and the damage shows up somewhere else, maybe in another player's game. A shallow copy is only safe when the shared inner objects never change. A deep copy creates new copies of every mutable part as well. Immutable values, like strings, enums or records with immutable fields, can safely be shared, which is one more reason to prefer immutable parts.

Shallow vs deep
  • shallow copy:
  • new outer object, same inner
  • objects. Fine only if the
  • inner objects never change
  • deep copy:
  • new outer object AND new
  • copies of every mutable part
  • immutable parts (String,
  • records) can be shared

Deep copy in code

The deep copy, written as a copy constructor. It takes another game level and copies field by field. The name and theme are strings, which are immutable, so sharing them is fine. The spawn list is new, and each enemy spawn is copied with its own copy constructor. The loot map holds strings and integers, so a new hash map with the same entries is enough. The copy method simply calls this constructor.

GameLevel copy constructor
GameLevel(GameLevel other) {
  this.name = other.name;
  this.theme = other.theme;  // String
  this.spawns = new ArrayList<>();
  for (EnemySpawn s : other.spawns)
    spawns.add(new EnemySpawn(s));
  this.loot = new HashMap<>(other.loot);
}
GameLevel copy() {
  return new GameLevel(this); }

Copying vs clone()

Why not just use clone? Java's clone is awkward. The Cloneable interface has no methods. It only switches on the behaviour of object dot clone, which is protected and throws a checked exception. Clone creates the object without running any constructor. And because it copies fields after construction, final fields cannot be reassigned to deep copies. A copy constructor or a copy method is plain, readable Java with none of these surprises.

Why clone() is awkward
  • Cloneable has no methods;
  • it just switches clone() on
  • Object.clone() is protected
  • and throws a checked
  • CloneNotSupportedException
  • it skips constructors
  • final fields cannot be
  • reassigned for a deep copy
  • copy constructor: plain code

Prototype registry

A prototype registry makes this tidy. It keeps a map from names to master levels. Register stores a copy, so the caller cannot change the master afterwards. Create looks up the name and returns another copy, so the caller can never change the master either. The slow load happens once per master at startup. After that, each new level costs only a copy in memory.

LevelRegistry
private final Map<String, GameLevel>
    masters = new HashMap<>();

void register(String key, GameLevel g) {
  masters.put(key, g.copy()); }

GameLevel create(String key) {
  GameLevel m = masters.get(key);
  if (m == null) throw ...;
  return m.copy();
}

Run-through

Follow one request. The editor asks the registry for desert. The registry finds the master and calls copy. The copy constructor builds a new level with its own spawn list and its own enemies. The editor names it desert hard and doubles every enemy's health. Then it asks for desert again, for the night version. That copy starts from the untouched master, with normal health, because nothing was shared.

When to use it

Use the prototype pattern when setting an object up is slow, like reading files, querying a database or running a long calculation, when you need many small variations of the same thing, or when objects are configured at runtime by users rather than defined by classes. Avoid it when creating from scratch is cheap. Be careful with object graphs that have cycles, or that hold resources like open sockets, which cannot be meaningfully copied.

Use or avoid
  • use when:
  • • setup is slow (files, DB,
  • long calculations)
  • • many small variations
  • • objects are configured at
  • runtime, not by class
  • avoid when:
  • • new is cheap and simple
  • • graphs with cycles or
  • shared resources (sockets)

In Java

In the Java library, array list dot clone returns a shallow copy: a new list holding the same element objects. The copy constructors, new array list or new hash map from another collection, are shallow in the same way. Cloning an array of ints is a complete copy, because ints are values, but cloning an array of objects is shallow. List copy of gives an immutable shallow copy. So whenever elements are mutable, copy them yourself.

Where you see it
  • arrayList.clone()
  • shallow: elements shared
  • new ArrayList<>(other)
  • new HashMap<>(other)
  • copy constructors, shallow
  • int[] b = a.clone();
  • fine for primitives
  • List.copyOf(list)
  • immutable shallow copy

Neighbours

Compare it with its neighbours. Factories choose a class and build a fresh object. A builder assembles one object step by step and checks it. Prototype starts from an existing, already configured object. A registry of prototypes can even replace a factory: instead of one class per variant, you keep configured instances. One warning: Spring's prototype scope only means a new bean on every request. It does not copy anything, it just shares the name.

How it differs
  • factory method / abstract
  • factory: pick a class,
  • build fresh
  • builder: assemble step by
  • step, then check
  • prototype: start from an
  • existing, configured object
  • Spring "prototype" scope:
  • a new bean each time, NOT
  • a copy (same name only)

In LLD interviews

In interviews, prototype fits templates and presets: game levels and enemy types, document or email templates, configuration presets per customer. It also appears when you need snapshots, like copying a chess board to try a move for undo or for an engine's lookahead. The two classic mistakes are a shallow copy of mutable parts, and returning the master object itself instead of a copy.

Where it comes up
  • game levels, enemy presets
  • document or email templates
  • chess board snapshots for
  • undo or AI lookahead
  • config presets per tenant
  • mistakes:
  • • shallow copy of mutable
  • parts
  • • handing out the master

Interview questions

What is the prototype pattern?

A creational pattern where new objects are made by copying an existing, already configured object instead of building from scratch. The object provides a copy method because it knows its own fields and which parts need deep copying.

What is the difference between a shallow and a deep copy?

A shallow copy creates a new outer object but copies references to the inner objects, so both share them. A deep copy also creates new copies of the mutable inner objects, so changing one object never affects the other.

Why is clone() in Java considered problematic?

Cloneable has no methods and only changes how Object.clone behaves; Object.clone is protected and throws a checked CloneNotSupportedException. It creates objects without running constructors, is shallow by default, and cannot deep copy into final fields. Copy constructors or copy methods avoid all of this.

Is ArrayList.clone() a deep copy?

No. It returns a new ArrayList that holds the same element objects, so changing an element through one list is visible through the other. The same is true of new ArrayList(other) and List.copyOf, which only differ in mutability of the list itself.

Do immutable fields need to be deep copied?

No. Immutable objects such as String, Integer, enums and records with immutable fields can be shared safely between the original and the copy, since neither can change them. Only mutable parts need fresh copies.

What is a prototype registry?

A map from names to configured master objects. Callers ask for a name and receive a copy, so masters are created once, never handed out, and can never be changed by a caller. It can replace a family of factory subclasses with configured instances.

When is the prototype pattern a good choice?

When creating an object is expensive, such as loading files or querying a database, when you need many small variations of the same setup, or when object configurations are defined at runtime. It is not worth it when creation is cheap.

Is Spring prototype scope the same as the prototype pattern?

No. Prototype scope means the container creates a new bean instance for each request instead of sharing one. It does not copy an existing object, so it is unrelated to the pattern apart from the name.