Prototype
Creating objects by cloning existing ones — shallow vs deep copies, copy constructors, prototype registries, and how JavaScript's prototype chain relates.
Intent: create new objects by copying an existing instance (the prototype) rather than constructing from scratch.
Useful when:
- Creating an object is expensive (loaded from disk, computed, configured through many steps) and you need many similar ones.
- You need copies of an object whose concrete class you don't know (you only hold an interface).
- You want preset configurations to start from (a "template" document, game enemies with base stats).
Shallow vs deep copy
The crucial detail. A shallow copy duplicates the top-level object but shares nested objects; a deep copy duplicates everything recursively.
Mutating shallow.tags also changes original.tags — a classic bug.
// Prefer copy constructors or static copy factories over Cloneable (which is widely considered broken).
public class Document {
private String title;
private final List<String> tags;
private final Style style; // mutable nested object
public Document(String title, List<String> tags, Style style) {
this.title = title; this.tags = tags; this.style = style;
}
// Deep copy constructor
public Document(Document other) {
this.title = other.title; // String is immutable: sharing is fine
this.tags = new ArrayList<>(other.tags); // new list
this.style = new Style(other.style); // copy nested mutable object
}
public Document copy() { return new Document(this); }
}
Document template = loadTemplate("invoice");
Document invoice = template.copy();
invoice.setTitle("Invoice #42"); // template unaffectedimport copy
class Document:
def __init__(self, title, tags, style):
self.title, self.tags, self.style = title, tags, style
template = Document("Invoice", ["finance"], Style(font="Inter"))
shallow = copy.copy(template) # new Document, but same tags list and style
deep = copy.deepcopy(template) # everything duplicated (handles cycles too)
deep.tags.append("draft") # template.tags unchanged
shallow.tags.append("oops") # template.tags now includes "oops"!
# Customise copying with __copy__ / __deepcopy__ if some fields must be shared (e.g. a DB connection).interface Doc { title: string; tags: string[]; style: { font: string } }
const template: Doc = { title: "Invoice", tags: ["finance"], style: { font: "Inter" } };
const shallow = { ...template }; // spread = shallow copy
const deep = structuredClone(template); // built-in deep copy (no functions/classes)
shallow.tags.push("oops"); // also mutates template.tags!
deep.tags.push("draft"); // safe
// Classes: give them an explicit clone()
class Enemy {
constructor(public hp: number, public pos: { x: number; y: number }) {}
clone() { return new Enemy(this.hp, { ...this.pos }); }
}Prototype registry
Keep a map of pre-configured prototypes and clone on demand:
class ShapeRegistry:
def __init__(self):
self._protos = {}
def register(self, key, proto):
self._protos[key] = proto
def create(self, key):
return copy.deepcopy(self._protos[key])
registry.register("big-red-circle", Circle(radius=50, color="red"))
c = registry.create("big-red-circle")Prototype and JavaScript
JavaScript is a prototype-based language: objects inherit directly from other objects via the prototype chain (Object.create(proto)). That's related in spirit — new objects are based on existing ones — but it's delegation, not copying: the new object looks up missing properties on its prototype at runtime (Prototypes & classes).
- Prototype creates objects by copying an existing instance.
- Shallow copies share nested objects; deep copies duplicate them — know which you need.
- Java: use copy constructors; Python:
copy.deepcopy; JS:structuredClone. - Immutable objects never need copying — another argument for immutability.