Prototype Pattern

Prototype produces a new object by copying an existing, already-configured one instead of running a constructor. Two honest things up front: it is the least-used creational pattern in modern Java, and the interface the JDK shipped for it – Cloneable – is a standard example of a Java design mistake, taught mainly so you know to avoid it. The idea underneath survives both facts, because the idea was never “implement an interface named Cloneable”. It is copy semantics: deciding, one reference field at a time, what a copy owns outright and what it shares with the object it came from.

💡 Shallow copy = a new object whose reference fields point at the same objects the original’s point at. Deep copy = a new object whose reference fields point at copies of those objects, recursively. “Recursively” is where all the interesting arguments live.

Why this matters: that decision shows up far more often than the pattern’s name does – in undo, in defensive copying at an API boundary, in test fixtures, and in every object graph you hand to code you do not control. An interviewer asking how you would implement Prototype is almost never asking for clone(); they are checking whether you understand copy semantics. The bug that bad copying causes has no stack trace. You ask for a copy, you get something that passes !=, every field reads back the value you expect, and three operations later editing one object has quietly edited four – while every test asserting on the top-level fields still passes. So what gets graded is whether you can name the decision you made for each field, and whether “just deep copy the whole thing” survives a graph holding a database connection and a cycle.


Prerequisites

  • Immutability and Equality – an immutable object never needs copying, which makes it the escape hatch from this whole problem rather than a nice-to-have
  • Builder Pattern – the pattern Prototype gets compared against, and where a defensive copy inside a constructor already appears
  • Memento Pattern – the same deep-versus-shallow decision applied to archived state, where the shallow version is the same silent bug

The Problem: 200 reports that share one Map

A ReportTemplate is expensive to build. Its constructor reads a layout file off disk and parses it, resolves a stylesheet and flattens its inheritance, then pre-computes a column index so lookups during rendering are O(1). The application needs 200 slightly different reports per run: same layout, same styles, a different title and a couple of parameters each. There are two obvious ways to get them and both are wrong:

public class ReportTemplate {
    private final Layout layout;                     // parsed from XML on disk
    private final StyleSheet styles;                 // resolved, styles flattened
    private final Map<String, Integer> columnIndex;  // derived from layout
    private String title;                            // the three that vary
    private List<Section> sections;                   // per report
    private Map<String, String> params;

    // Option B's "copy". It compiles, it returns a new object, and it is wrong.
    public ReportTemplate shallowCopy() {
        ReportTemplate c = new ReportTemplate(layout, styles, columnIndex);
        c.title = this.title;        // String is immutable, so this one is fine
        c.sections = this.sections;  // the SAME List object, not a copy
        c.params = this.params;      // the SAME Map object, not a copy
        return c;
    }
}

// Option A: construct one per report. 200 reports, 200 parses.
for (ReportRequest r : requests) render(new ReportTemplate(LAYOUT, STYLE).titled(r.title()));

// Option B: build once, hand out shallow copies.
ReportTemplate base = new ReportTemplate(LAYOUT, STYLE);
ReportTemplate q1 = base.shallowCopy(), q2 = base.shallowCopy();
q1.params.put("region", "APAC");
q2.params.put("region", "EMEA");
q1.params.get("region");          // "EMEA" -- q1, q2 and base share one Map
q1.sections.add(new Section("Appendix"));
base.sections.size();             // grew too. Nothing threw.

Three costs, and an interviewer will press on all three:

  1. Option A pays for the same work 200 times. The parse, the stylesheet resolution and the index build are identical every iteration; none depend on the request. The expensive part of construction is the part that never varies, which is the exact condition that makes copying worth considering.
  2. Option B’s copy is not a copy; it is a second name for the same state. q1 and q2 are distinct objects holding references to one List and one Map. Filling in one report’s parameters fills in all of them, and adding a section to a copy mutates the prototype every later copy is made from. Nothing throws, and a test that checks assertNotSame(q1, q2) and compares titles goes green.
  3. shallowCopy has no enforced relationship to the fields it copies. Add a footerTemplate tomorrow and the compiler says nothing, so the copy method and the class drift apart silently, and drift again with every field added after that.

Class Diagram

classDiagram
    class Prototype {
        <<interface>>
        +copy() Prototype
    }
    class ReportTemplate {
        -Layout layout
        -StyleSheet styles
        -Map~String, Integer~ columnIndex
        -String title
        -List~Section~ sections
        -Map~String, String~ params
        -ReportTemplate(ReportTemplate source)
        +copy() ReportTemplate
    }
    class Section {
        -String heading
        -List~Row~ rows
        +copy() Section
    }
    class Layout
    class PrototypeRegistry {
        -Map~String, ReportTemplate~ prototypes
        +register(String name, ReportTemplate p)
        +create(String name) ReportTemplate
    }

    Prototype <|.. ReportTemplate
    Prototype <|.. Section
    ReportTemplate --> Section : copies each element
    ReportTemplate ..> Layout : shares by reference
    PrototypeRegistry --> ReportTemplate

Two things carry this design, and neither is copy(). First, there are two kinds of outgoing edge: the solid line into Section is a field ReportTemplate recurses into because Section is mutable, while the dashed line into Layout is shared by reference because Layout is immutable. The arrows say where copying stops. Second, the private constructor taking its own type is the copy constructor; copy() just wraps it.


Real-World Example: Report Template with a Copy Constructor

public final class ReportTemplate {
    private final Layout layout;                     // expensive + immutable
    private final StyleSheet styles;                 // expensive + immutable
    private final Map<String, Integer> columnIndex;  // derived + immutable
    private String title;                            // the per-report fields,
    private final List<Section> sections;            // and sections is mutable
    private final Map<String, String> params;

    /** The expensive path: one parse per layout, not one per report. */
    public ReportTemplate(Path layoutFile, Path styleFile) {
        this.layout = LayoutParser.parse(layoutFile);              // read + validate
        this.styles = StyleSheetResolver.resolve(styleFile, layout);
        this.columnIndex = Map.copyOf(layout.columnPositions());   // unmodifiable
        this.title = layout.defaultTitle();
        this.sections = new ArrayList<>(layout.defaultSections());
        this.params = new HashMap<>();
    }

    /** Copy constructor. The comment on each line is the deliverable. */
    private ReportTemplate(ReportTemplate src) {
        this.layout = src.layout;            // SHARE: immutable, and the cost we dodge
        this.styles = src.styles;            // SHARE: no mutators, no mutable fields
        this.columnIndex = src.columnIndex;  // SHARE: derived, already unmodifiable
        this.title = src.title;              // SHARE: String, so assignment IS the copy
        // COPY, and one level is not deep enough: this copy will add sections, and
        // Section is mutable, so each element runs its own copy constructor. Inside
        // Section the recursion stops, because a Row is a record.
        this.sections = new ArrayList<>(src.sections.size());
        for (Section s : src.sections) this.sections.add(s.copy());
        // COPY: this copy will put params. Keys and values are Strings, so one
        // level is exactly deep enough and the recursion stops here.
        this.params = new HashMap<>(src.params);
    }

    public ReportTemplate copy()             { return new ReportTemplate(this); }
    public ReportTemplate titled(String t)   { this.title = t; return this; }
    public void putParam(String k, String v) { params.put(k, v); }
}

/** Variants by name, each handed out as a copy. */
public final class PrototypeRegistry {
    private final Map<String, ReportTemplate> prototypes = new HashMap<>();

    public void register(String name, ReportTemplate p) { prototypes.put(name, p); }

    public ReportTemplate create(String name) {
        ReportTemplate p = prototypes.get(name);
        if (p == null) throw new NoSuchElementException("no prototype: " + name);
        return p.copy();      // a COPY -- returning p itself is the bug above
    }
}

// Startup: one parse per template.
PrototypeRegistry registry = new PrototypeRegistry();
registry.register("sales-monthly", new ReportTemplate(SALES_LAYOUT, CORP_STYLE));

// Per request: 200 copies, zero parses, no shared mutable state.
for (ReportRequest r : requests) {
    ReportTemplate t = registry.create(r.templateName()).titled(r.title());
    t.putParam("region", r.region());     // this copy's own map
    render(t);
}
import copy, logging
from dataclasses import dataclass, replace

class ReportTemplate:
    def __init__(self, layout: "Layout", styles: "StyleSheet") -> None:
        self.layout = layout                        # expensive, immutable: share
        self.styles = styles                        # immutable: share
        self._column_index = layout.column_index()  # derived, immutable: share
        self.title = layout.default_title
        self.sections: list["Section"] = []         # per-report: copy
        self.params: dict[str, str] = {}            # per-report: copy
        self._log = logging.getLogger(__name__)     # a service: never copy

    def __copy__(self) -> "ReportTemplate":     # what copy.copy(t) calls, and
        clone = object.__new__(ReportTemplate)  # what you get by default anyway
        clone.__dict__.update(self.__dict__)    # every field aliased: Option B's bug
        return clone

    # What copy.deepcopy(t) calls. `memo` maps id(original) -> copy, and it IS
    # the identity map that makes cyclic graphs copyable: the second time
    # deepcopy meets an object it returns the copy already in memo instead of
    # recursing forever -- the library hands you the cycle fix as an argument.
    def __deepcopy__(self, memo: dict[int, object]) -> "ReportTemplate":
        clone = object.__new__(ReportTemplate)
        memo[id(self)] = clone     # register BEFORE recursing, or a section
                                   # holding a back-reference loops
        clone.layout, clone.styles = self.layout, self.styles   # share
        clone._column_index = self._column_index                # share
        clone.title = self.title                                # str: immutable
        clone.sections = copy.deepcopy(self.sections, memo)     # pass memo down
        clone.params = dict(self.params)   # str keys and values: one level is enough
        clone._log = self._log             # share it; never clone a logger
        return clone

# ---- The alternative that needs no copy method at all ----
@dataclass(frozen=True, slots=True)
class ReportSpec:
    layout_id: str
    title: str

base = ReportSpec(layout_id="sales-monthly", title="Sales")
q1 = replace(base, title="Sales Q1")   # new objects; base untouched, and no
q2 = replace(base, title="Sales Q2")   # aliasing is expressible here at all
# replace() calls __init__ with the changed fields substituted, so __post_init__
# validation runs again -- exactly what clone() skips.
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

// Copying through a Report& slices off the derived part, so polymorphic
// copying needs a virtual hook. clone() is that hook.
class Report {
public:
    virtual ~Report() = default;
    virtual std::unique_ptr<Report> clone() const = 0;
protected:
    Report() = default;
    Report(const Report&) = default;   // protected: outside code cannot slice
};

class SalesReport final : public Report {
    std::shared_ptr<const Layout> layout_;        // immutable and expensive:
    std::shared_ptr<const StyleSheet> styles_;    // SHARED, and const says so
    std::string title_;                           // value members, so the
    std::vector<Section> sections_;                // implicit copy constructor
    std::unordered_map<std::string, std::string> params_;  // already deep-copies

public:
    SalesReport(std::shared_ptr<const Layout> layout,   // parsed once, then
                std::shared_ptr<const StyleSheet> styles)   // shared by copies
        : layout_(std::move(layout)), styles_(std::move(styles)),
          title_(layout_->defaultTitle()), sections_(layout_->defaultSections()) {}

    // Rule of three / five: no raw owning pointers, so the generated copy, move
    // and destructor are correct and `= default` is the honest answer. Declare
    // one by hand and you own all five -- and one that forgets a member is the
    // stale-copy bug in C++ form.
    SalesReport(const SalesReport&) = default;
    SalesReport(SalesReport&&) noexcept = default;

    // unique_ptr is NOT a covariant return type -- only raw pointers and
    // references may covary -- so the virtual returns unique_ptr<Report> and
    // constructs the derived type inside it. Callers need no cast.
    std::unique_ptr<Report> clone() const override {
        return std::make_unique<SalesReport>(*this);   // the copy constructor
    }
};

// Why the pattern is rarer in C++: value semantics. `SalesReport b = a;` is
// already a member-wise copy and std::vector<Section> copies its elements, so
// clone() is needed only for objects held polymorphically through a base
// pointer, the case a copy constructor cannot serve.

Notice what the Java tab does not implement. Cloneable is absent on purpose, for four reasons: it declares no clone() method, so it is a marker that changes what the protected Object.clone() does rather than an interface you can program against; clone() runs no constructor, so final fields cannot be assigned and no invariant is established; its copy is shallow by contract, making the aliasing bug above the default; and it breaks under inheritance, since every class in the chain must cooperate while each clone() must still yield the right runtime type. Effective Java Item 13: “a better approach to object copying is to provide a copy constructor or copy factory.”


There is no such thing as “a deep copy” – only a copy deep enough

“Deep” is not a property of a copy routine. It is a decision made once per reference field, and the right answer differs for each one. Ask for a deep copy and most people describe recursion that runs until it hits a primitive. Run that on a real object and it either does something expensive and pointless or it does not terminate. You do not want to clone the database connection, the logger or the 400 MB lookup table every instance shares – the first two are meaningless to duplicate, the third is why the process has memory headroom. And if two objects reference each other, the recursion never returns.

The rule that drives the choice:

  • Copy what the new object may mutate: here sections and params, which exist precisely so each report can differ.
  • Share what is immutable: layout, styles, columnIndex, every String, every record. This is not a shortcut you are getting away with; it is correct, and it is the whole performance win.
  • Re-resolve what is a service – a logger, a connection pool, a clock. These are not state, so the copy gets the same one the original has.

💡 Aliasing = two references reaching the same object, so a write through one is visible through the other. A shallow copy of a mutable field is an alias with a reassuring name.

Three mechanisms, three different bills:

  1. Hand-written copy constructors. Correct, verbose, and the only mechanism where the decision per field is visible in the source. Also the only one that survives a new field being added – if something catches the omission, which for a mutable field is not the compiler.
  2. Serialization round-trip. Write the object to bytes, read it back. Genuinely deep, and it handles cycles for free because the format carries back-references. The costs are real: orders of magnitude slower than field assignment, every class must be serializable, and transient fields come back as type defaults silently, so a cached index becomes null. Deserialization also bypasses constructors, reintroducing clone()’s worst property by another route.
  3. Immutable objects with with-style methods. The modern answer, and the first to reach for, because an immutable object needs no copy. withTitle("Sales Q1") returns a new object sharing every field it did not change, and a shared field nobody can write is not an alias bug waiting to happen – see Immutability and Equality.

The cycle problem is the standard follow-up. If the graph can contain cycles – a Section pointing back at its template, a tree with parent pointers, anything loaded from a database – the fix is an identity map from each original to its copy, threaded through the recursion: look the object up, return the existing copy if it is there, register the new copy before recursing into children. That is what copy.deepcopy’s memo dict is, so sketch it rather than hand-waving.

The same “deep enough” question drives the Memento pattern, where getting it wrong means the archived snapshot mutates with the live object and undo restores the present. That lesson works the undo case through in detail.


Prototype vs Builder vs Factory Method vs Memento vs Flyweight

All five hand you an object you did not construct inline. What separates them is where it comes from:

Pattern Intent Tell
Prototype Produce a new object by copying a configured one Starts from an existing instance. Nothing happens until something exists to copy
Builder Assemble one object step by step Starts from nothing and accumulates. build() validates at the end
Factory Method Let a subclass or parameter decide which class to instantiate Starts from a type decision. The input is a discriminator, not a configuration
Memento Copy state so the originator can be restored into it Archived, never used live. Nobody outside the originator may read it
Flyweight Cut memory by sharing one instance per distinct value Deliberately does not copy. The exact opposite trade

The overlap worth naming is Prototype and Builder: a builder you keep around and call build() on repeatedly is already doing Prototype’s job, since the builder is the configured thing and each build() is the copy. Keep it when build() is cheap; move to a prototype registry when the expensive work happens before build(). Prototype and Flyweight pair instructively too, because both need you to know which fields are immutable – Flyweight so that sharing is safe, Prototype to know which fields it can leave shared instead of copying. Same analysis, opposite conclusions about how many objects you hold.


When to Use vs When to Avoid

Use Prototype When Avoid When
Construction is expensive – parsing, I/O, index building – and the result varies only in cheap fields Construction is a few field assignments, so a constructor or Builder reads better
The configuration is the hard part and already exists as a live, validated object The configuration is better expressed as data passed to a constructor
You need many near-identical objects at runtime: templates, test fixtures, game entities, board setups The objects are immutable, so the original can simply be shared
Callers pick a variant by name at runtime and a registry beats a switch over types The variants are known at compile time and a factory is clearer
A caller must not reach the object you handed out, so you return a defensive copy The graph holds sockets, threads or open files – anything whose identity is its meaning

The characteristic failure mode is the copy method that goes stale. Someone adds a footerTemplate field; the constructors get updated because the compiler insists; the copy path does not, and from then on every copy either leaves the field at its default or shares it with its source – silently, with no exception and no failing assertion. Make the fields final and the compiler becomes a partial test, since a constructor leaving a final field unassigned does not compile; that is the strongest argument for a copy constructor over a copy() that fills in a blank instance. For the mutable fields, the ones a prototype exists to vary, nothing checks you. Three mitigations, in increasing order of what they buy: a copy constructor listing every field in declaration order, so a reviewer can diff it against the class at a glance; a reflection-based test asserting every declared field of a copy is either a different object from the source’s or of an immutable type, which is the only one that actually fails when someone forgets; and fewer mutable fields, the real fix, since a field that cannot change neither needs copying nor can be aliased.


Interview Questions

  1. “Why does modern Java avoid Cloneable?” – Give the four specifics above, in this order, because vagueness is what is being tested: no clone() method on the interface, no constructor run so final fields and invariants are not established, shallow by contract, and broken under inheritance. Then close with Effective Java Item 13 – copy constructor or copy factory – and note that the two JDK-adjacent habits that look like exceptions, ArrayList.clone() and array clone(), are shallow too.

  2. “How do you copy an object graph with cycles?” – Thread an identity map through the recursion, populated before you recurse into children so a back-reference finds the partially built copy instead of looping. Use an IdentityHashMap, not a HashMap, because equals on a half-copied graph can recurse or be expensive and two equal-but-distinct nodes must stay distinct.

  3. “Is deep copy via serialization a good answer?” – It is the common interview shortcut and it falls apart under two follow-ups. transient fields come back as type defaults with no warning, so a lock or a cached index silently becomes null, and the whole graph has to be serializable, which in practice it is not. It is also orders of magnitude slower than field assignment, since you pay reflection plus a full encode and decode to produce an object already in memory. Defensible as a one-off in a test, or where you already serialize for another reason.

  4. “Prototype vs Memento?” – What the copy is for, which changes the API more than the copying code. A prototype’s copy is a live object handed to a caller who will use and mutate it, so it must be independent, fully usable and publicly typed. A memento is archived state the originator restores itself from, so it is deliberately opaque and only has to be deep enough to reconstruct state. Identical machinery, opposite visibility: one comes back as ReportTemplate, the other as a marker interface with no methods.

  5. “How does copy-on-write change the calculus?” – It makes the copy O(1) and defers the real cost to the first write, so 200 reports that each change only a title pay for just what they touch. Persistent data structures generalise this – a copy is a new root plus the single changed path, O(log n) – which is why Prototype largely disappears in languages built on them: there is nothing left to copy. The catch is that it needs a single writer or genuine immutability underneath, and the Java class advertising it, CopyOnWriteArrayList, copies the whole array on every write: right for a listener list, wrong for a hot write path.


See It in Action

  • Spreadsheet Engine – copy and paste a range: each cell is copied, the shared style object is not
  • Deck of Cards – one pristine 52-card deck registered and copied per game, so shuffling one table cannot reorder another
  • Mini Version Control – branching copies a tree, affordable because unchanged subtrees are shared
  • E-commerce Cart – a “reorder” starts as a copy of a past order, and the nested line-item list is where aliasing bites