Prototype creates new objects by copying an existing one. Every object that can be copied implements a clone() method from a common interface, so code that needs a copy just asks the object for one, without knowing its concrete class and without repeating the setup that configured it. The hard part is not the idea but the copy itself: a clone that shares a nested object with its original (a shallow copy) is one of the most common bugs in object-oriented code, and this lesson shows it happening.
Think of it like
A key cutting machine
To get a spare house key you do not tell the locksmith the cut depths of every pin. You hand over the key you have, and the machine traces it and cuts a copy. The locksmith never needs to know which lock it opens or how it was first made. The original key is the prototype, tracing and cutting is clone(), and the shop works the same way for any key you bring, even a kind it has never seen.
The problem
A drawing editor lets the user select a shape and press Ctrl+D to duplicate it; the copy then becomes the selection. The editor holds the selection as a Shape, but to make a copy it has to call a constructor, and a constructor belongs to one concrete class. So the first version checks the class and rebuilds the copy from the shape's fields. This is the Before version of the Clone scenario in the visualizer above.
interface Shape {
area(): number;
}
class Circle implements Shape {
constructor(public radius: number, public color: string) {}
area() {
return Math.round(Math.PI * this.radius ** 2);
}
}
class Rect implements Shape {
constructor(public w: number, public h: number, public color: string) {}
area() {
return this.w * this.h;
}
}
class Editor {
constructor(private selected: Shape) {}
duplicate(): Shape {
const s = this.selected;
let copy: Shape;
if (s instanceof Circle) copy = new Circle(s.radius, s.color);
else if (s instanceof Rect) copy = new Rect(s.w, s.h, s.color);
else throw new Error("shape?");
this.selected = copy;
return copy;
}
}- The editor depends on every shape class. A triangle, a star or a text box each needs another
instanceofbranch inEditor, and a forgotten branch only shows up at run time, as thethrow. - Encapsulation leaks. To rebuild a circle from outside, the editor must read all of its fields, so they become public (or grow getters). Add a field to
Circleand the copy silently drops it until someone also editsEditor. - Subclasses get sliced. A
RoundedRect extends Rectpasses theinstanceof Rectcheck, so its "copy" comes back as a plainRectwith the rounding lost. - The switch spreads. Copy and paste, undo snapshots, templates and "save as" all need copies, and each grows its own type check.
There is a second, quieter cost. Objects are often configured at run time: a shape the user styled by hand, an enemy whose stats were loaded from a data file, a report whose settings took a database query to compute. Building another one "from scratch" means knowing and repeating every step of that setup. Copying a configured instance and then changing the one or two fields that differ is simpler and often cheaper.
The pattern
Intent (paraphrasing the Gang of Four book): specify the kinds of objects to create with a prototypical instance, and create new objects by copying that prototype.
- Prototype (
Shape) - The interface that declares
clone(). Code that needs copies depends only on this. - Concrete prototype (
Circle,Rect) - A class that implements
clone()by building a new instance of itself with a copy of its own state. It is the only code that knows its class and its private fields. - Client (
Editor) - Asks an existing object to clone itself, then uses or adjusts the copy. It never names a concrete class.
- Prototype registry (optional)
- A map from a name to a preconfigured prototype, so clients can say
create("orc")and get a fresh copy. See Variations.
interface Shape {
area(): number;
clone(): Shape;
}
class Circle implements Shape {
constructor(private radius: number, private color: string) {}
area() {
return Math.round(Math.PI * this.radius ** 2);
}
clone(): Circle {
return new Circle(this.radius, this.color);
}
}
class Editor {
constructor(private selected: Shape) {}
select(s: Shape) {
this.selected = s;
}
duplicate(): Shape {
const copy = this.selected.clone(); // no instanceof, no new
this.selected = copy;
return copy;
}
}The copying moved into the class being copied. That is the whole trick: clone() is a polymorphic copy, sometimes called a virtual copy constructor. The caller dispatches on the object it already holds, the same way it would call area(), and the object answers with a new instance of its own class, private fields included. Editor shrinks to one line and never changes again when shapes are added.
What the visualizer shows
- Clone scenario, class diagram:
Editorholds aShapethrough itsselectedfield;CircleandRectimplement it. Whenduplicate()callsclone(), the interfaceShapelights violet (it declares the method) andCircleamber (its code runs). In Before, dashed «create» arrows run fromEditorto every shape class instead. - Clone scenario, objects:
edpoints at its selection. With Prototype the clone call goes fromedtoc, andcitself createsc2; in Before,edcreatesc2directly. After each duplicate,selectedmoves to the copy. - Shallow vs deep scenario: a
Circlewith a nestedStyleobject. With the shallow clone, the objects view showscircleandcircle2both pointing at onestyle, and recoloring the copy turns the original red. With the deep clone,stylecreatesstyle2, each circle has its own, and the original stays blue.
Press Play in the visualizer at the top of the page, or step with the arrow buttons: it really runs the classes in the code panel. The Clone / Shallow vs deep switch in the toolbar picks the scenario. In Clone, the Before / With Prototype toggle compares the instanceof version with the pattern, and Add triangle applies the change request; the Change request panel beside the code counts what each version had to edit. In Shallow vs deep, Before is the shallow clone and With deep clone the fix. On a phone, the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Set up the originals
In Clone with With Prototype selected, the client creates
c(a blueCircleof radius 5),r(a green 4 × 2Rect) and the editored, which starts withcselected. - 2
Ask the selection to copy itself
ed.duplicate()callsthis.selected.clone(). The editor holds aShape; the object is aCircle, soCircle.clone()runs. - 3
The prototype creates its copy
ccreatesc2with its own radius and color, and returns it.ed.selectednow points toc2, as an editor selects a fresh duplicate. - 4
Same line, other class
ed.select(r)and anothered.duplicate(): the very same line now dispatches toRect.clone(), andrcreatesr2. - 5
Add triangle (change request)
With Add triangle applied, the new
Trianglebrings its ownclone(), andduplicate()copies it unchanged. In Before,Editorhas to grow a thirdinstanceofbranch first. - 6
Shallow clone
Switch to Shallow vs deep, Before.
circle.clone()passesthis.styleto the new circle, socircle2.styleandcircle.styleare the same object.circle2.recolor("red")setsstyle.color, andcircle.getColor()now returns"red"too. - 7
Deep clone
With deep clone:
Circle.clone()callsthis.style.clone()first, sostylecreatesstyle2. Recoloring the copy changes onlystyle2;circle.getColor()still returns"blue".
Before and after
Without the pattern
- The copier checks
instanceofand calls each class's constructor - Every field the copy needs must be readable from outside
- A new shape means editing
Editoras well as adding the class - Subclasses that pass a parent's check are copied as the parent
- No
clone()to write in each class
With Prototype
- The copier calls
clone()and never names a concrete class - Fields stay private: each class copies its own state
- A new shape is a new class with a
clone(), nothing else - A subclass that overrides
clone()copies as itself - Every class must implement
clone(), and get its depth right
| Change request: add triangle | Before | With Prototype |
|---|---|---|
| Existing classes edited | 1 (Editor) | 0 |
| New classes | 1 (Triangle) | 1 (Triangle) |
| Lines changed in existing classes | 3 (+3 −0) | 0 |
Three lines is a small edit, but it lands in the class every duplicate goes through, and it has to be repeated in every other place that copies shapes. With the pattern the new class is a little larger (it carries its own clone()), and nothing else is touched.
Variations
Shallow vs deep copy
A shallow copy duplicates the object's fields one by one: numbers and strings are copied, and references are copied as references, so the copy and the original point at the same nested objects. A deep copy also copies the objects those references lead to (and so on down), so the two share nothing mutable. The Shallow vs deep scenario shows the difference in a single field:
class Style {
constructor(public color: string) {}
clone() {
return new Style(this.color);
}
}
class Circle {
constructor(private radius: number, private style: Style) {}
shallowClone() {
return new Circle(this.radius, this.style); // shares the Style
}
clone() {
return new Circle(this.radius, this.style.clone()); // owns a copy
}
recolor(c: string) {
this.style.color = c;
}
}| Field holds | In the clone | Why |
|---|---|---|
A primitive (number, boolean) | Copy the value | Values cannot be shared |
| An immutable object (a string, a date-time value object, a frozen config) | Copy the reference | Nobody can change it, so sharing is safe and cheaper |
A mutable object the original owns (Style, a list of points) | Clone it | Otherwise a change through one object shows up in the other |
| A collection the original owns | A new collection, with owned elements cloned | Copying only the collection still shares the elements |
| A shared resource or a back-reference (a texture, a logger, the parent document) | Copy the reference, on purpose | The copy should use the same resource or belong to the same parent |
Copy constructors
A copy constructor takes an instance of its own class, new Circle(other), and copies its fields. It is explicit and works with final fields, but on its own it is not polymorphic: you have to name the class, which is exactly what the Editor could not do. The two combine well: each clone() is a one-liner that calls its own copy constructor (return new Circle(this)). In C++ the compiler writes the copy constructor for you, and it copies members by value, so a member held by value is copied deeply and a member held through a pointer is not.
Prototype registry
When the set of things to create is data rather than code, keep a registry of named, preconfigured prototypes and clone from it: a game loads orc, goblin and orc-chief from a file at startup, and the spawner calls registry.create("orc"). New kinds are new entries, not new classes, because an orc chief is just an orc prototype with more health and better loot. The second implementation below is a registry; its spawn() always returns a clone, never the stored prototype itself.
| Variation | How it works | Watch out for |
|---|---|---|
| Cloning object graphs with cycles | A deep copy keeps a map from each original object to its copy, and reuses the copy when it meets the same object again (Python's deepcopy passes this memo map; structuredClone does the same internally) | A naive recursive clone() loops forever on a cycle, and copies an object twice when two fields point at it |
| Immutable prototypes | If the object can never change, sharing it is as good as copying it. Create variants with copy-with-changes methods such as withColor("red") that return a new object | There is nothing to clone: Prototype is mostly about mutable objects |
| Cloning a Composite | A tree clones itself by cloning each child and attaching the copies to the new parent | The children's parent references must point to the new parent, not the old one |
structuredClone in JavaScript | A built-in deep copy of plain data: objects, arrays, Map, Set, Date, typed arrays, with cycles handled | Class instances come back as plain objects (the prototype chain is not copied), and functions or DOM nodes throw a DataCloneError |
In real code
| Where | Mechanism | Notes |
|---|---|---|
| Java | Object.clone() and the Cloneable marker interface | Object.clone() is protected and makes a shallow field-by-field copy; on a class that does not implement Cloneable it throws CloneNotSupportedException. Effective Java (Item 13, "Override clone judiciously") lists its problems and recommends a copy constructor or copy factory instead; arrays are the exception where clone() is fine |
| Python | copy.copy(x) and copy.deepcopy(x) from the standard copy module | A class customizes them with __copy__ and __deepcopy__(self, memo); deepcopy uses the memo dictionary to handle recursive structures and shared references |
| C++ | A virtual clone() returning std::unique_ptr<Base> | The standard idiom for copying through a base pointer, usually implemented as std::make_unique<Derived>(*this), which reuses the copy constructor. Covariant return types work for raw pointers but not for std::unique_ptr |
| JavaScript | structuredClone(value) | Built into browsers and Node.js (version 17 and later) for deep copies of plain data, as described above |
| Game engines | Prefabs | A designer configures an object once (mesh, components, settings) and the game spawns copies of it at run time. Unity's Object.Instantiate(original) is documented as cloning the original object |
In application code, look for "duplicate", "copy", "save as template" and "new from template" features: duplicating a slide or a spreadsheet tab, creating an issue from a template, starting a document from a saved layout. Undo systems also take copies, though when the copy is a snapshot of internal state kept for later, that is Memento.
When to use it, and when not to
Reach for Prototype when
- Code must copy objects whose concrete class it does not know (duplicate, copy and paste, templates)
- Objects are configured at run time and building another from scratch would repeat expensive or complicated setup
- Variants differ only in data, so a registry of configured prototypes replaces a subclass per variant
- You would otherwise write a type switch to copy
Skip it when
- The objects are immutable: share them, or use
withX()methods - The caller knows the class anyway: a copy constructor or a plain
newis clearer - Objects hold resources that must not be duplicated (open sockets, file handles, locks)
- The object graph is large and full of cycles and shared parts, so deciding what to copy is harder than building anew
Prototype vs similar patterns
| Pattern | How it makes objects | Choose it when |
|---|---|---|
| Prototype | Copies an existing, configured instance through clone() | The class is unknown to the caller, or the configuration is the expensive part |
| Factory Method | A subclass overrides a method that calls new | A base class must create objects that subclasses choose; Prototype needs no creator subclass per product |
| Abstract Factory | A factory object creates a family of matching products | Products must match; a factory can itself be built from prototypes, one per product |
| Builder | Assembles one complex object step by step | Construction has many optional parts; a builder can also start from a clone of a preset |
| Memento | Captures an object's internal state in an opaque snapshot | You need to restore an object later (undo). Both copy state, but a memento is not a working object and only its originator can read it |
| Flyweight | Shares one immutable instance among many users | Many objects have identical state. It is the opposite choice: Prototype copies so objects can diverge, Flyweight shares because they never will |
Implementation
The visualizer's two scenarios in one program: an Editor that duplicates the selected shape through the Shape interface, and shapes that hold a mutable Style and clone it, so recoloring a copy leaves the original unchanged.
from __future__ import annotations
import math
from abc import ABC, abstractmethod
class Style:
def __init__(self, color: str) -> None:
self.color = color
def clone(self) -> Style:
return Style(self.color)
class Shape(ABC):
def __init__(self, style: Style) -> None:
self.style = style
def recolor(self, color: str) -> None:
self.style.color = color
@abstractmethod
def area(self) -> int: ...
@abstractmethod
def describe(self) -> str: ...
@abstractmethod
def clone(self) -> Shape: ...
class Circle(Shape):
def __init__(self, radius: int, style: Style) -> None:
super().__init__(style)
self.radius = radius
def area(self) -> int:
return round(math.pi * self.radius**2)
def describe(self) -> str:
return f"{self.style.color} circle, r={self.radius}"
def clone(self) -> Circle:
# Deep: the copy gets its own Style.
return Circle(self.radius, self.style.clone())
class Rect(Shape):
def __init__(self, w: int, h: int, style: Style) -> None:
super().__init__(style)
self.w = w
self.h = h
def area(self) -> int:
return self.w * self.h
def describe(self) -> str:
return f"{self.style.color} rect, {self.w}x{self.h}"
def clone(self) -> Rect:
return Rect(self.w, self.h, self.style.clone())
class Editor:
"""The client: copies any Shape without knowing its class."""
def __init__(self, selected: Shape) -> None:
self.selected = selected
def select(self, shape: Shape) -> None:
self.selected = shape
def duplicate(self) -> Shape:
copy = self.selected.clone()
self.selected = copy # the duplicate becomes the selection
return copy
if __name__ == "__main__":
c = Circle(5, Style("blue"))
r = Rect(4, 2, Style("green"))
ed = Editor(c)
c2 = ed.duplicate()
c2.recolor("red")
print(c.describe()) # blue circle, r=5
print(c2.describe()) # red circle, r=5
ed.select(r)
r2 = ed.duplicate()
print(r2.describe(), r2.area()) # green rect, 4x2 8Key takeaways
- Prototype creates objects by copying an existing instance through a
clone()method declared on a common interface, so the caller needs neither the concrete class nor the setup steps. - The copy logic lives in the class being copied, which knows its own class and private fields: a polymorphic, or virtual, copy constructor.
- In the visualizer's "Add triangle" request, the
instanceofversion editsEditor(+3 lines) as well as addingTriangle; with Prototype onlyTriangleis added. - A shallow copy shares nested objects with the original; changing one changes both. Clone what the object owns and is mutable, share what is immutable or meant to be shared.
- A registry of named, configured prototypes turns variants into data: a new kind of enemy or document is a new entry, not a new class.
- JavaScript's prototype chain is delegation, not copying. It shares a name with the pattern, not its mechanics.
Common pitfalls
- Shipping a shallow
clone()for an object with mutable nested state, so editing the copy silently changes the original (and the bug appears far from the copy). - Handing out the stored prototype itself from a registry instead of a clone, so the first caller who modifies it changes every future copy.
- Recursive deep copies of object graphs with cycles or shared parts: without a map of already copied objects they loop forever or duplicate shared objects.
- Using Java's
Cloneableandsuper.clone()without care: the default copy is shallow,finalfields cannot be reassigned to fresh copies, and the method throws a checked exception. Prefer a copy constructor or copy factory. - Forgetting
clone()in a subclass: the inherited one returns a copy of the parent class, which slices away the subclass's state.
Interview tips
- Explain the motivation in one sentence: "copy this object without knowing its class", then show
duplicate()before (a type switch) and after (selected.clone()). - Expect "shallow vs deep copy" as the follow-up. Draw two objects with arrows into one shared nested object, then the fix, and mention immutable fields and cycles.
- Know the language tools:
copy.deepcopyin Python, copy constructors andCloneablein Java (and why Effective Java avoids it), a virtualclone()returningstd::unique_ptrin C++,structuredClonein JavaScript. - In LLD rounds, a prototype registry fits games (enemy and item templates), document editors (templates) and configuration presets.
Real-world applications
- Duplicate, copy and paste, and "new from template" features in editors for drawings, slides, spreadsheets and documents.
- Spawning game entities from configured templates (prefabs), such as enemies, bullets and particles.
- Presets and configuration templates: a base configuration cloned and adjusted per environment or per customer.
- Test fixtures: a fully built sample object cloned for each test so tests cannot leak changes into one another.
- Copying plain data in JavaScript with
structuredClone, and Python object graphs withcopy.deepcopy.
Test yourself
In the editor example, why can Editor.duplicate() copy a Triangle without being edited?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.