On this page

Prototype

Most creational patterns answer "which class should I instantiate?" Prototype sidesteps the question. Instead of constructing a new object, you copy one that already exists and is already set up the way you want. The object being copied, the prototype, knows how to duplicate itself, so the caller needs neither its concrete class nor the steps that configured it.

That sounds trivial, because "copy an object" is one line in most languages. It isn't. The hard part of Prototype is deciding what a copy means: which fields get duplicated, which are shared, and which must be reset. Get that wrong and you end up with the most common copying bug there is: two objects that look independent but secretly share a list, so editing one changes the other. This page spends real time on that problem. It also covers why Java's built-in clone() is widely considered broken, what Python's copy module and JavaScript's structuredClone actually do, and when copying is the right way to create objects at all. The creational patterns page has a short dashboard-widget example. This page goes deeper.

CategoryCreational
SolvesCreating objects that are variations of a configured instance, or copying objects whose concrete type you don't know
Main costDefining correct copy semantics for every class, especially with nested mutable state
Modern formsCopy constructors, copy() methods, copy.deepcopy, structuredClone, records with with/replace

Intent

Specify the kinds of objects to create by using a prototypical instance, and create new objects by copying that prototype.

Two distinct needs lead here, and it helps to keep them apart:

  1. Polymorphic copying. You hold a reference typed as an interface (Task, Shape, Widget) and need a duplicate of the same concrete type, without an instanceof chain.
  2. Configured templates. Creating an object from scratch is slow or involved (loading, parsing, many settings), and new objects are mostly the same as a template with a few changes.

The problem

A project-management tool lets teams save a sprint as a template, such as "Release sprint" with standard tasks and checklists, and start new sprints from it. Tasks come in different kinds (stories, bugs), each with its own fields. Here is the first attempt at "create a sprint from a template".

import java.util.*;

interface Task { String title(); }

final class Story implements Task {
    final String title; final int points; final List<String> checklist;
    Story(String title, int points, List<String> checklist) { this.title = title; this.points = points; this.checklist = checklist; }
    public String title() { return title; }
}

final class Bug implements Task {
    final String title; final String severity; final List<String> checklist;
    Bug(String title, String severity, List<String> checklist) { this.title = title; this.severity = severity; this.checklist = checklist; }
    public String title() { return title; }
}

class SprintFactory {
    // Problem 1: the copier must know every concrete Task class.
    // Problem 2: it passes the same checklist list to the copy (a shallow copy).
    static List<Task> fromTemplate(List<Task> template) {
        List<Task> sprint = new ArrayList<>();
        for (Task t : template) {
            if (t instanceof Story s) sprint.add(new Story(s.title, s.points, s.checklist));
            else if (t instanceof Bug b) sprint.add(new Bug(b.title, b.severity, b.checklist));
            else throw new IllegalArgumentException("don't know how to copy " + t.getClass());
        }
        return sprint;
    }
}

public class Before {
    public static void main(String[] args) {
        List<Task> template = List.of(new Story("Release notes", 2, new ArrayList<>(List.of("Draft", "Review"))));
        List<Task> sprint42 = SprintFactory.fromTemplate(template);

        ((Story) sprint42.get(0)).checklist.add("Translate to German");   // edit the new sprint...

        Story original = (Story) template.get(0);
        if (!original.checklist.contains("Translate to German")) throw new AssertionError("bug should reproduce");
        System.out.println("the template changed too: " + original.checklist);
    }
}
import copy
from dataclasses import dataclass, field


@dataclass
class Story:
    title: str
    points: int
    checklist: list[str] = field(default_factory=list)


@dataclass
class Sprint:
    name: str
    tasks: list[Story]


template = Sprint("Release sprint", [Story("Release notes", 2, ["Draft", "Review"])])

sprint42 = copy.copy(template)          # looks like a copy...
sprint42.name = "Sprint 42"
sprint42.tasks[0].checklist.append("Translate to German")

assert template.name == "Release sprint"                       # top-level field: independent
assert "Translate to German" in template.tasks[0].checklist     # nested list: shared
print("template checklist changed:", template.tasks[0].checklist)

Two problems are visible:

  • The copier knows every concrete class. Each new task type (spike, chore, epic) means editing fromTemplate. That violates the open/closed principle and ties the factory to every subclass.
  • The copy is shallow. The new Story gets a reference to the same ArrayList as the template's story. Editing the sprint edits the template, and every future sprint created from it. Python's copy.copy has exactly the same behaviour: the top-level object is new, but everything it points to is shared.

The pattern's fix is to move copying into each class. Each task type knows its own fields, so it's the only place that can copy itself correctly, and callers just call copy() through the interface.

Structure

classDiagram
    class Task {
        <<interface>>
        +copy() Task
        +title() String
    }
    class Story {
        -points int
        -checklist List
        +copy() Story
    }
    class Bug {
        -severity String
        -checklist List
        +copy() Bug
    }
    class TemplateRegistry {
        -prototypes Map
        +register(name, task)
        +create(name) Task
    }
    class Client
    Task <|.. Story
    Task <|.. Bug
    TemplateRegistry o-- Task : holds prototypes
    Client --> TemplateRegistry : asks for a copy
    Client ..> Task : uses

The client asks the registry for a named template, and the registry calls copy() on the stored prototype. Neither the client nor the registry names a concrete task class. The covariant return type (Story.copy() returns Story) is a nicety Java and TypeScript allow, so code that already knows it has a Story doesn't need a cast.

Participants

  • Prototype (Task). Declares the copy operation.
  • Concrete prototypes (Story, Bug). Implement copy() and decide, field by field, what a copy means.
  • Client. Creates new objects by asking a prototype to copy itself, then adjusts the copy.
  • Prototype registry (TemplateRegistry, optional). Stores named prototypes and hands out copies on request. It works like a factory whose "products" are configured at run time rather than coded as classes.

Implementation

The three implementations below fix both problems. Each task copies itself and gets a new checklist and a new ID. Each copy also shares one field on purpose: the reporter, a User, is an identity, not part of the task's own state. Copying a task shouldn't create a second user.

import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

record User(String name) {}                          // identity-bearing, immutable: share it

interface Task {
    Task copy();
    long id();
    String title();
    List<String> checklist();
    User reporter();
}

abstract class BaseTask implements Task {
    private static final AtomicLong IDS = new AtomicLong();
    private final long id;
    private final String title;
    private final List<String> checklist;           // owned, mutable: deep-copy it
    private final User reporter;                    // shared reference: keep it

    protected BaseTask(String title, List<String> checklist, User reporter) {
        this.id = IDS.incrementAndGet();
        this.title = title;
        this.checklist = new ArrayList<>(checklist);
        this.reporter = reporter;
    }

    // Copy constructor: runs real constructor logic, so the copy gets a new id.
    protected BaseTask(BaseTask other) { this(other.title, other.checklist, other.reporter); }

    public long id() { return id; }
    public String title() { return title; }
    public List<String> checklist() { return checklist; }
    public User reporter() { return reporter; }
}

final class Story extends BaseTask {
    private final int points;
    Story(String title, int points, List<String> checklist, User reporter) { super(title, checklist, reporter); this.points = points; }
    private Story(Story other) { super(other); this.points = other.points; }
    @Override public Story copy() { return new Story(this); }    // covariant return
    int points() { return points; }
}

final class Bug extends BaseTask {
    private final String severity;
    Bug(String title, String severity, List<String> checklist, User reporter) { super(title, checklist, reporter); this.severity = severity; }
    private Bug(Bug other) { super(other); this.severity = other.severity; }
    @Override public Bug copy() { return new Bug(this); }
    String severity() { return severity; }
}

final class TemplateRegistry {
    private final Map<String, List<Task>> templates = new HashMap<>();

    void register(String name, List<Task> tasks) {
        List<Task> frozen = new ArrayList<>();
        for (Task t : tasks) frozen.add(t.copy());     // store our own copies, too
        templates.put(name, List.copyOf(frozen));
    }

    List<Task> create(String name) {
        List<Task> prototypes = templates.get(name);
        if (prototypes == null) throw new IllegalArgumentException("no template " + name);
        List<Task> sprint = new ArrayList<>();
        for (Task t : prototypes) sprint.add(t.copy()); // polymorphic: no instanceof
        return sprint;
    }
}

public class Main {
    static void check(boolean condition, String message) { if (!condition) throw new AssertionError(message); }

    public static void main(String[] args) {
        User asha = new User("Asha");
        TemplateRegistry registry = new TemplateRegistry();
        registry.register("release", List.of(
            new Story("Release notes", 2, List.of("Draft", "Review"), asha),
            new Bug("Smoke-test regressions", "high", List.of("Run suite"), asha)));

        List<Task> sprint42 = registry.create("release");
        List<Task> sprint43 = registry.create("release");
        sprint42.get(0).checklist().add("Translate to German");

        check(!sprint43.get(0).checklist().contains("Translate to German"), "copies are independent");
        check(!registry.create("release").get(0).checklist().contains("Translate to German"), "template untouched");
        check(sprint42.get(0).id() != sprint43.get(0).id(), "each copy gets a new id");
        check(sprint42.get(0).reporter() == sprint43.get(0).reporter(), "reporter is shared on purpose");
        check(sprint42.get(1) instanceof Bug b && b.severity().equals("high"), "concrete type preserved");
        System.out.println("sprint 42: " + sprint42.get(0).checklist() + ", sprint 43: " + sprint43.get(0).checklist());
    }
}
import copy
import itertools
from dataclasses import dataclass, field
from typing import Any, Self

_ids = itertools.count(1)


@dataclass(frozen=True)
class User:                               # identity-bearing and immutable: share it
    name: str


@dataclass
class Task:
    title: str
    checklist: list[str]
    reporter: User
    id: int = field(default_factory=lambda: next(_ids))

    def copy(self) -> Self:
        return copy.deepcopy(self)

    def __deepcopy__(self, memo: dict[int, Any]) -> Self:
        # Customise deepcopy: new id, deep-copied checklist, shared reporter.
        clone = copy.copy(self)                         # shallow copy keeps the subclass and its fields
        memo[id(self)] = clone
        clone.checklist = copy.deepcopy(self.checklist, memo)
        clone.id = next(_ids)
        # clone.reporter is left pointing at the same User
        return clone


@dataclass
class Story(Task):
    points: int = 1


@dataclass
class Bug(Task):
    severity: str = "medium"


class TemplateRegistry:
    def __init__(self) -> None:
        self._templates: dict[str, list[Task]] = {}

    def register(self, name: str, tasks: list[Task]) -> None:
        self._templates[name] = [t.copy() for t in tasks]

    def create(self, name: str) -> list[Task]:
        try:
            return [t.copy() for t in self._templates[name]]
        except KeyError:
            raise ValueError(f"no template {name!r}") from None


asha = User("Asha")
registry = TemplateRegistry()
registry.register("release", [
    Story("Release notes", ["Draft", "Review"], asha, points=2),
    Bug("Smoke-test regressions", ["Run suite"], asha, severity="high"),
])

sprint42, sprint43 = registry.create("release"), registry.create("release")
sprint42[0].checklist.append("Translate to German")

assert "Translate to German" not in sprint43[0].checklist
assert "Translate to German" not in registry.create("release")[0].checklist
assert sprint42[0].id != sprint43[0].id
assert sprint42[0].reporter is sprint43[0].reporter is asha
assert isinstance(sprint42[1], Bug) and sprint42[1].severity == "high"
print("sprint 42:", sprint42[0].checklist, "sprint 43:", sprint43[0].checklist)
import assert from "node:assert/strict";

type User = Readonly<{ name: string }>;     // identity-bearing and immutable: share it
let nextId = 1;

interface Task {
  readonly id: number;
  readonly title: string;
  readonly checklist: string[];
  readonly reporter: User;
  copy(): Task;
}

class Story implements Task {
  readonly id = nextId++;
  constructor(readonly title: string, readonly points: number, readonly checklist: string[], readonly reporter: User) {}
  copy(): Story {
    // New id (from the field initialiser), fresh checklist array, same reporter.
    return new Story(this.title, this.points, [...this.checklist], this.reporter);
  }
}

class Bug implements Task {
  readonly id = nextId++;
  constructor(readonly title: string, readonly severity: string, readonly checklist: string[], readonly reporter: User) {}
  copy(): Bug {
    return new Bug(this.title, this.severity, [...this.checklist], this.reporter);
  }
}

class TemplateRegistry {
  readonly #templates = new Map<string, readonly Task[]>();
  register(name: string, tasks: readonly Task[]): void {
    this.#templates.set(name, tasks.map((t) => t.copy()));
  }
  create(name: string): Task[] {
    const prototypes = this.#templates.get(name);
    if (!prototypes) throw new Error(`no template ${name}`);
    return prototypes.map((t) => t.copy());          // polymorphic: no instanceof
  }
}

const asha: User = { name: "Asha" };
const registry = new TemplateRegistry();
registry.register("release", [
  new Story("Release notes", 2, ["Draft", "Review"], asha),
  new Bug("Smoke-test regressions", "high", ["Run suite"], asha),
]);

const sprint42 = registry.create("release");
const sprint43 = registry.create("release");
sprint42[0].checklist.push("Translate to German");

assert.ok(!sprint43[0].checklist.includes("Translate to German"));
assert.ok(!registry.create("release")[0].checklist.includes("Translate to German"));
assert.notEqual(sprint42[0].id, sprint43[0].id);
assert.equal(sprint42[0].reporter, sprint43[0].reporter);
assert.ok(sprint42[1] instanceof Bug && sprint42[1].severity === "high");
console.log("sprint 42:", sprint42[0].checklist, "sprint 43:", sprint43[0].checklist);

Notice that the registry copies on the way in as well as on the way out. If it stored the caller's objects directly, the caller could later mutate a stored prototype by accident. This is the same defensive-copy discipline as an immutable class taking a list in its constructor.

Shallow and deep copies: the core of the pattern

A shallow copy creates a new top-level object whose fields hold the same references as the original. A deep copy recursively copies everything reachable, so the two object graphs share nothing. Neither is correct by default. A correct copy usually mixes three treatments, field by field:

TreatmentApplies toExampleWhy
ShareImmutable values; references to other entities; servicesreporter: User, a String, a LocalDate, a loggerImmutable data can't be corrupted by sharing, and copying a reference to another entity must not clone that entity
Copy (deep)Mutable state the object ownschecklist, a nested list of subtasks, a map of settingsOtherwise the original and the copy alias the same data
ResetIdentity and bookkeepingid, createdAt, version, caches, locks, open handlesA copy is a new thing: it needs its own identity and fresh caches

Getting this wrong produces three classic bugs:

  1. Aliasing: a shallow copy shares an owned mutable collection, as in the "before" code. It's the most common one, and it often stays hidden until much later, when someone edits a copy.
  2. Over-copying: a blanket deep copy clones things that should be shared. Deep-copying a task would also deep-copy its reporter, creating a second "Asha" that no longer == the real user, and that won't see later changes to her account. Deep-copying an object that holds a database connection or a lock is worse, either failing outright or producing a nonsense duplicate.
  3. Identity duplication: the copy keeps the original's ID, so saving it overwrites the original, or two "different" rows collide on a unique key.

Cycles and shared substructure

Object graphs often contain cycles (a task points to its sprint, the sprint lists its tasks) or shared nodes (two tasks with the same parent). A naive recursive copy loops forever on a cycle, and turns one shared node into two separate copies. Python's copy.deepcopy handles both with its memo dictionary, which maps id(original) to the copy already made. That's why a custom __deepcopy__ must register the clone in memo before copying children, as the example above does. JavaScript's structuredClone also preserves cycles and shared references. Hand-written copy() methods in Java and TypeScript need the same idea (an IdentityHashMap or Map from original to copy) if the graph can contain cycles.

Java's clone(): why copy constructors are preferred

Java built Prototype into the language with Object.clone() and the Cloneable interface. Nearly everyone who writes about Java design, notably Joshua Bloch in Effective Java, recommends avoiding it in new code. The reasons:

  • Cloneable has no methods. It's a marker that changes the behaviour of a protected method on Object. Implementing it doesn't give callers a public clone(), so you can't call clone() through an interface type at all without declaring it yourself.
  • It's shallow by default. super.clone() copies field values bit by bit, so every mutable field is aliased, which is exactly the bug above.
  • It doesn't run constructors. Any invariant or bookkeeping a constructor performs (assigning a fresh ID, registering a listener, validating) is skipped.
  • It fights final fields. To deep-copy a field after super.clone(), you must reassign it, which you can't do if the field is final. So clone() pushes you toward mutable fields.
  • It throws a checked exception (CloneNotSupportedException) that callers must handle even when it can't happen.
  • Subclassing is fragile. Every class in the hierarchy must cooperate by calling super.clone() correctly. One class that uses a constructor instead breaks the chain.

This example shows the first three problems, then the fix:

import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

final class CloneableTask implements Cloneable {
    static final AtomicLong IDS = new AtomicLong();
    final long id;
    List<String> checklist;                         // can't be final if clone() must replace it

    CloneableTask(List<String> checklist) { this.id = IDS.incrementAndGet(); this.checklist = checklist; }

    @Override public CloneableTask clone() {
        try {
            return (CloneableTask) super.clone();  // shallow, and skips the constructor
        } catch (CloneNotSupportedException e) {
            throw new AssertionError(e);           // can't happen, but must be handled
        }
    }
}

final class CopyableTask {
    static final AtomicLong IDS = new AtomicLong();
    final long id;
    final List<String> checklist;                  // stays final

    CopyableTask(List<String> checklist) { this.id = IDS.incrementAndGet(); this.checklist = new ArrayList<>(checklist); }
    CopyableTask(CopyableTask other) { this(other.checklist); }  // copy constructor: runs real init
    static CopyableTask copyOf(CopyableTask other) { return new CopyableTask(other); }
}

public class CloneProblems {
    public static void main(String[] args) {
        CloneableTask a = new CloneableTask(new ArrayList<>(List.of("Draft")));
        CloneableTask b = a.clone();
        b.checklist.add("Review");
        if (!a.checklist.contains("Review")) throw new AssertionError("clone() should alias the list");
        if (a.id != b.id) throw new AssertionError("clone() should skip the constructor and keep the id");

        CopyableTask c = new CopyableTask(List.of("Draft"));
        CopyableTask d = CopyableTask.copyOf(c);
        d.checklist.add("Review");
        if (c.checklist.contains("Review")) throw new AssertionError("copy constructor must not alias");
        if (c.id == d.id) throw new AssertionError("copy constructor gives a new id");

        int[] arr = {1, 2, 3};
        int[] arrCopy = arr.clone();               // arrays are the one place clone() is fine
        arrCopy[0] = 99;
        if (arr[0] != 1) throw new AssertionError("array clone is independent for primitives");
        System.out.println("clone() aliased and kept the id; the copy constructor did neither");
    }
}

The alternatives are a copy constructor (new Story(other)) or a static copy factory (Story.copyOf(other)), plus a polymorphic copy() method on the interface that delegates to them, as in the main implementation. They run real constructor logic, work with final fields, throw no checked exceptions and make the copy semantics explicit in code you can read. The JDK's own collections follow this style: new ArrayList<>(other), new HashMap<>(other), List.copyOf(other). Arrays are the exception, where array.clone() is the idiomatic copy (shallow for arrays of objects).

Python: copy, deepcopy and the hooks

  • copy.copy(x) makes a shallow copy. list.copy(), dict.copy(), slicing (xs[:]) and dataclasses.replace(obj, ...) are shallow too.
  • copy.deepcopy(x) copies recursively, using a memo dictionary to handle cycles and shared references.
  • A class controls its copying with __copy__(self) and __deepcopy__(self, memo). Use __deepcopy__ to share fields that must not be cloned (references to other entities, locks, connections) and to reset identity, as the Task example does.
  • Objects that can't be copied meaningfully, such as open files, sockets, locks and generators, make deepcopy raise or produce something useless. If your object holds one, define __deepcopy__ to share or recreate it.
  • Python 3.13 added copy.replace(obj, **changes), a general "copy with changes" for objects that support it (dataclasses, named tuples and others). On older versions, use dataclasses.replace or namedtuple._replace.

JavaScript and TypeScript: spread, structuredClone and its limits

  • Spread and Object.assign ({ ...task }, [...list]) are shallow. They're perfect for one level of copying, as in the copy() methods above, and are how React and Redux code produces new state objects.
  • structuredClone(value), available in modern browsers and in Node 17 and later, performs a deep copy using the structured clone algorithm. It handles nested objects, arrays, Map, Set, Date, RegExp, typed arrays, and cycles.
  • But it is not a general object copier. Class instances come back as plain objects (the prototype and therefore every method is lost), functions cause a DataCloneError, getters are evaluated into plain values, and DOM nodes can't be cloned this way. So structuredClone is right for data, and wrong as the implementation of copy() on a class.
  • JSON.parse(JSON.stringify(x)) is the old trick, and it's lossier still: Dates become strings, Map and Set become {}, undefined fields disappear and cycles throw.
import assert from "node:assert/strict";

class Task {
  constructor(public title: string, public checklist: string[], public due: Date) {}
  describe(): string { return `${this.title} (${this.checklist.length} items)`; }
}

const original = new Task("Release notes", ["Draft"], new Date("2026-12-20"));

// Deep data is copied: nested array and Date are new objects.
const cloned = structuredClone(original);
cloned.checklist.push("Review");
assert.deepEqual(original.checklist, ["Draft"]);
assert.ok(cloned.due instanceof Date && cloned.due !== original.due);

// ...but the class is gone: it's a plain object without methods.
assert.ok(!(cloned instanceof Task));
assert.equal((cloned as Partial<Task>).describe, undefined);

// Cycles and Maps are fine.
const graph: { name: string; self?: unknown; tags: Map<string, number> } = { name: "g", tags: new Map([["a", 1]]) };
graph.self = graph;
const g2 = structuredClone(graph);
assert.equal(g2.self, g2);
assert.equal(g2.tags.get("a"), 1);

// Functions can't be cloned.
assert.throws(() => structuredClone({ run: () => 1 }), (e: Error) => e.name === "DataCloneError");

// JSON round-trip loses even more.
const viaJson = JSON.parse(JSON.stringify({ due: new Date(0), tags: new Map([["a", 1]]), gone: undefined }));
assert.equal(typeof viaJson.due, "string");
assert.deepEqual(viaJson.tags, {});
assert.ok(!("gone" in viaJson));
console.log("structuredClone copies data, not classes or functions");

JavaScript is also a prototype-based language, in which objects inherit directly from other objects through the prototype chain (Object.create(proto)). That's a related but different idea: a JavaScript prototype is delegated to, not copied. Changing a property on the prototype later is visible through every object that inherits from it. The GoF pattern creates independent copies.

Real-world uses

JDK

  • Object.clone() with Cloneable, used by ArrayList, HashMap, ArrayDeque, Date and arrays, all of which return shallow copies.
  • Copy constructors and copy factories throughout the collections: new ArrayList<>(c), new TreeMap<>(sortedMap), List.copyOf, Map.copyOf, EnumSet.copyOf.

Spring

  • The prototype bean scope creates a new instance every time the bean is requested. Despite the name, Spring builds it from the bean definition instead of cloning an existing object, so it's closer to a factory than to the GoF Prototype. It's a good trivia point in interviews.

.NET

  • Object.MemberwiseClone() is a protected shallow copy, like Java's clone().
  • ICloneable exists, but it doesn't say whether Clone() is deep or shallow. Microsoft's framework design guidelines recommend not implementing it in public APIs for that reason.
  • C# records support with expressions (var copy = original with { Points = 3 };), a built-in, shallow "copy with changes" for immutable data.

Python

  • The copy module (copy, deepcopy, __copy__, __deepcopy__), plus list.copy(), dict.copy(), dataclasses.replace and, since 3.13, copy.replace.

Browser, Node and React

  • structuredClone (browsers and Node 17+), also used internally to pass data through postMessage to workers.
  • The DOM's node.cloneNode(deep) copies an element, optionally with its whole subtree. HTML <template> content is typically cloned (template.content.cloneNode(true)) to stamp out new elements from a prototype. That's the pattern almost exactly.
  • React state updates are copy-with-changes: setTask({ ...task, title }) creates a new object rather than mutating the old one. Libraries such as Immer automate it with structural sharing, copying only the parts that changed.

When NOT to use it, and the costs

  • The object is immutable. Immutable objects never need copying, so share them. "Copy with changes" for immutable objects is better done with withers, toBuilder() or with/replace, which create a new object from validated parts.
  • Construction is cheap and simple. If new Story(title, points) is all it takes, copying an existing story is just an indirect way of calling the constructor.
  • The object holds external resources such as connections, file handles, threads or locks. A copy either shares them (with surprising results) or can't meaningfully duplicate them. Create a new object properly instead.
  • The object is an entity with strong identity, such as an account or an order, where "a copy" isn't a meaningful domain operation. If the domain does need it ("duplicate this order"), model it explicitly as a domain method that resets identity and status, not as a generic clone().
  • The graph is large and deeply shared. Deep-copying big object graphs is slow and memory-hungry. Structural sharing (persistent data structures, Immer) is usually better.

Costs:

CostWhy it matters
Copy semantics per classEvery class must decide share, copy or reset for every field, and keep it right as fields are added
Subtle bugsAliasing and identity duplication often surface far from the copy
Hidden expenseA deep copy may touch thousands of objects
Subclass burdenEvery subclass must override copy(). Forgetting means a Bug copy silently becomes a BaseTask or loses fields
  • Factory Method. Chooses the class to create through subclasses. Prototype gets the same flexibility without subclassing the creator: give the creator a prototype object instead.
  • Abstract Factory. A concrete factory can store a set of prototypes and return copies, which allows families defined at run time (user-created themes or templates) without a class per family.
  • Builder. toBuilder() is another way to start from an existing object and change a few things, with validation running again at build(). Prefer it for immutable objects. Prefer Prototype when the type is unknown to the caller.
  • Memento. Saves a snapshot of an object's state for undo. A memento is often made by copying, and has the same shallow-versus-deep concerns.
  • Composite. Copying a composite means deep-copying its children. "Duplicate this folder" or "duplicate this group of shapes" is Prototype applied to a tree.
  • Flyweight. The opposite instinct: Flyweight shares immutable intrinsic state across many objects to save memory, while Prototype copies state to make independent objects. A good copy implementation shares exactly the flyweight-like (immutable) parts.
  • Command. Command histories sometimes store copies of commands, or copies of the state they changed, so Prototype often appears inside undo systems.

The smell that suggests it

  • An instanceof or type-switch chain whose only purpose is to duplicate an object of the matching class.
  • "Duplicate", "save as template" or "start from existing" features in the requirements.
  • The same expensive setup repeated to produce objects that differ in one or two fields.
  • Bugs where editing one object changes another, a sign that someone made a shallow copy without realising it.
  • Many near-identical subclasses that exist only to preset fields. Configured prototype instances in a registry can replace them.

Interview questions

  1. "What's the difference between a shallow and a deep copy?" Shallow copies the top-level object and shares every reference it holds. Deep copies everything reachable. Then add the important part: real copies are usually neither. You share immutable values and references to other entities, deep-copy owned mutable state, and reset identity.
  2. "Why is Java's clone() considered broken?" Cloneable is a marker without a public clone() method. Object.clone() is shallow, skips constructors, conflicts with final fields and throws a checked exception, and every class in the hierarchy must cooperate. Prefer copy constructors or static copy factories, with a polymorphic copy() if needed.
  3. "How does copy.deepcopy handle cycles?" It keeps a memo dictionary mapping each original object's id() to its copy. Before copying an object it checks the memo, so cycles and shared references are preserved. A custom __deepcopy__ should add its clone to the memo before copying children.
  4. "Can I use structuredClone to clone class instances?" It deep-copies the data, but returns plain objects without the class prototype or methods, and throws on functions. Use it for data, and write a copy() method for classes.
  5. "When would you use Prototype instead of a factory?" When the caller doesn't know the concrete type (polymorphic copying), when objects are configured at run time (templates created by users), or when building from scratch is expensive and new objects are variations of an existing one.
  6. "Your copied order still has the original's ID. What's wrong and how do you fix it?" Identity was copied instead of reset. A copy is a new entity, so the copy operation must assign a new ID and reset status, timestamps and version. Better still, make "duplicate order" an explicit domain method so those rules are visible and tested.
  7. "Is Spring's prototype scope the Prototype pattern?" Not really. It creates a fresh instance from the bean definition on every request rather than copying an existing instance. The shared idea is "a new object each time". The mechanism is a factory.
  8. "Where does Prototype appear in an LLD interview?" In "duplicate" features: copy a document, a board, a playlist or a form, or "clone this game piece". Also in editors (copy and paste of shapes) and when spawning game entities from templates. State your copy semantics explicitly: what's shared, what's copied, what's reset.

Further reading