Creational 4 — Prototype
In one line
Clone an existing instance instead of re-running expensive construction. Rare in interviews — know the intent, not the ceremony.
Think of it like this
Photocopying a filled-in form. Instead of filling out the whole form again, you copy one that's already done and change only the name.
Key ideas
- 01
Solves: copying fully-configured objects without rebuilding from scratch.
- 02
clone() is a prototype; in modern Java prefer copy constructors or static copy methods.
- 03
Deep copy vs shallow copy is the classic trap — know which fields are shared.
Java / Spring map
- →
Cloneable is widely considered legacy (Effective Java, Item 13). Prefer copy constructors or static copyOf() methods. Records are immutable, so they can be shared instead of copied.
Code & diagrams
A copy constructor with an explicit deep copy of mutable state, plus a prototype registry.
public final class Board {
private final Piece[][] cells;
public Board() { this.cells = new Piece[8][8]; }
// Copy constructor = prototype. Deep-copies the mutable grid.
public Board(Board other) {
this.cells = new Piece[8][];
for (int r = 0; r < 8; r++) this.cells[r] = other.cells[r].clone();
// Piece is immutable, so sharing Piece references is safe (shallow is OK here).
}
public Board copy() { return new Board(this); }
}
// Prototype registry: pre-configured templates cloned on demand.
public final class DocumentTemplates {
private final Map<String, Document> templates = new HashMap<>();
public void register(String key, Document d) { templates.put(key, d); }
public Document create(String key) { return templates.get(key).copy(); } // never hand out the original
}Explain without notes
When is cloning better than running a constructor?
Which fields must be deep-copied and which can safely be shared?
Practice
Model 'Board snapshot' cloning for the Chess LLD (for undo).
Trade-offs
- ↔
Shallow copies share mutable state silently — the classic bug.
Completion checklist
I can implement a correct deep copy and explain why immutable fields can be shared.