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.
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.
- 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.
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 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(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.
- 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.
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 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.
- 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.
- 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.
- 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