Skip to content

Prototype Pattern: Create Objects by Cloning a Configured Instance

Learn the Prototype pattern: build new objects by cloning a configured instance, and decide which fields get a deep copy and which stay shared.

12 min readDesign patternCreational

Specify the kinds of objects to create with a prototypical instance, and create new objects by asking that instance to copy itself. The copy must be independent wherever independence matters, and may share what is safe or intended to share.

Prototype is a creational pattern that makes new objects by copying an existing one instead of building them from scratch. The object knows how to clone itself, so the caller does not need to know its concrete class or how it was configured. In interviews it rarely comes up as a standalone pattern. It usually shows up inside a question about deep versus shallow copies, a bug where two objects quietly share a list, or a design for templates and duplication. This guide follows one product, a task-board app called Larkspur, from a broken duplicate button to a clean prototype registry. You will see where deep copies are required, where sharing a reference is the correct choice, and how to explain the difference under pressure.

The problem

A situation where the obvious design starts to hurt.

Larkspur is a task-board app used by about 900 workspaces. Its templates team maintains 14 board templates such as Bug triage, Content calendar and Hiring pipeline. Each template has between 6 and 10 columns, every column has a title and an optional WIP limit, and every board carries a set of labels. Boards also belong to a workspace, which holds billing and member data.

The first version of the New board handler had a 14-branch switch. Each branch constructed a board by hand, roughly 30 lines per template. Adding a template meant a code change and a deploy, and product wanted customers to save their own customised boards as templates, which no switch can know about in advance.

So a developer added a Duplicate button that copied the board with a field-by-field spread. It looked fine in review. Two weeks later a support ticket arrived: a customer lowered the WIP limit on the Investigating column of their new Mobile bugs board from 5 to 3, and every board created from the Bug triage template afterward also had a limit of 3. The copy had a new board object, but its columns array and the Column objects inside it were the same ones the template held. One edit leaked into the template and into every future board.

The team needs a way to create boards from any configured board, built-in or customer-made, without knowing its construction steps, and with copies that cannot corrupt the original.

The solution

What the pattern proposes.

Give the board a clone() method and let it decide how to copy itself. The New board handler no longer constructs anything. It asks a template registry for a board by key, the registry clones the stored prototype, and the handler renames the result.

The interesting part is what clone() copies. A Board has three kinds of fields. Primitive values like the name copy by value automatically. Mutable parts that belong to the board, the columns list, each Column inside it and the labels list, must be copied deeply, otherwise you get the WIP limit bug. References to things the board merely points at, like its Workspace, must stay shared: cloning a workspace would create a phantom tenant with its own members and billing.

So Board.clone builds a new Board, maps each column through Column.clone, copies the labels list, and passes the same workspace reference. Each class owns the copy rules for its own fields, so when Column later gains a list of automation rules, only Column.clone changes.

Customer-saved templates now work for free: saving a template means registering a clone of the customer's board under a new key. Nothing in the handler or the registry depends on concrete construction logic.

An everyday analogy

The same idea, outside software.

Think of a key-cutting kiosk at a hardware store. You hand over a key that already works, and the machine traces it to cut a new one. The kiosk does not need the lock maker's specifications or know which door the key opens; the original carries all the information needed to make the copy.

The copy is a separate piece of metal. If you file a notch on it or bend it, the original is untouched. That is the deep part. But both keys still open the same front door, because the lock itself is not duplicated. That is the shared part, and it is exactly what you want. A good clone copies what each holder must own and keeps pointing at what everyone is meant to share.

Structure

The pieces and how they relate.

Larkspur's template registry clones Board prototypes; columns and labels are deep-copied, the workspace reference is shared.NewBoardHandler calls TemplateRegistry (create(key, name)). TemplateRegistry has a Board (stored templates). TemplateRegistry calls Prototype<T> (clone()). Board implements Prototype<T>. Column implements Prototype<T>. Board has a Column (deep-copied). Board has a Workspace (shared reference).NewBoardHandlerasks for a board bytemplate key«interface»Prototype<T>clone(): TTemplateRegistryregister(key,board), create(key…Boardname, workspace,columns, labelsColumntitle, wipLimitWorkspaceid, name (nevercloned)Copy rulesDeep: columns,labels. Shared…create(key, name)stored templatesclone()deep-copiedshared reference
Larkspur's template registry clones Board prototypes; columns and labels are deep-copied, the workspace reference is shared.

Participants

Prototype (interface)
Declares clone(). Anything that can produce a copy of itself implements it, so callers can duplicate objects without knowing their concrete class.
Board (concrete prototype)
Implements clone() and decides, field by field, what gets copied deeply (columns, labels) and what stays shared (workspace).
Column (concrete prototype)
Owns the copy rules for its own fields. Board delegates to it, so new Column fields only require changes in Column.
Workspace
A shared collaborator. Copies keep pointing at the same instance on purpose; cloning it would create a fake tenant.
TemplateRegistry
Stores configured prototypes under keys and returns fresh clones. Built-in and customer-saved templates are registered the same way.
NewBoardHandler (client)
Requests boards by key and customises the copy. It never constructs a Board itself.

Pseudocode

The solution to the scenario, language-neutral.

interface Prototype<T>
    method clone(): T

class Column implements Prototype<Column>
    field title
    field wipLimit
    method clone()
        return new Column(title, wipLimit)

class Board implements Prototype<Board>
    field name
    field workspace          // shared, never copied
    field columns            // owned, copied deeply
    field labels             // owned, copied

    method clone()
        copiedColumns = empty list
        for each column in columns
            copiedColumns.add(column.clone())
        return new Board(name, workspace, copiedColumns, copy of labels)

class TemplateRegistry
    field templates = map from key to Board

    method register(key, board)
        templates[key] = board

    method create(key, name)
        template = templates[key]
        if template is missing
            fail "unknown template"
        board = template.clone()
        board.name = name
        return board

// client
registry.register("bug-triage", configuredBugTriageBoard)
mobile = registry.create("bug-triage", "Mobile bugs")
mobile.columns[1].wipLimit = 3    // template and other boards unaffected

The code

The same solution in TypeScript, Python and PHP.

interface Prototype<T> {
  clone(): T;
}

class Workspace {
  constructor(public readonly id: string, public readonly name: string) {}
}

class Column implements Prototype<Column> {
  constructor(public title: string, public wipLimit: number | null) {}

  clone(): Column {
    return new Column(this.title, this.wipLimit);
  }
}

class Board implements Prototype<Board> {
  constructor(
    public name: string,
    public readonly workspace: Workspace,
    public columns: Column[],
    public labels: string[],
  ) {}

  clone(): Board {
    return new Board(
      this.name,
      this.workspace, // shared on purpose: never duplicate a tenant
      this.columns.map((column) => column.clone()),
      [...this.labels],
    );
  }

  // The buggy version from the first Duplicate button, kept for comparison.
  shallowCopy(): Board {
    return new Board(this.name, this.workspace, this.columns, this.labels);
  }
}

class TemplateRegistry {
  private templates = new Map<string, Board>();

  register(key: string, board: Board): void {
    this.templates.set(key, board);
  }

  create(key: string, name: string): Board {
    const template = this.templates.get(key);
    if (!template) {
      throw new Error(`Unknown template: ${key}`);
    }
    const board = template.clone();
    board.name = name;
    return board;
  }
}

const acme = new Workspace("ws-17", "Acme Support");
const registry = new TemplateRegistry();
registry.register(
  "bug-triage",
  new Board(
    "Bug triage",
    acme,
    [new Column("New", null), new Column("Investigating", 5), new Column("Fixed", null)],
    ["p1", "p2", "regression"],
  ),
);

const mobile = registry.create("bug-triage", "Mobile bugs");
mobile.columns[1].wipLimit = 3;
mobile.labels.push("ios");

const web = registry.create("bug-triage", "Web bugs");
console.log(web.columns[1].wipLimit); // 5
console.log(web.labels.join(",")); // p1,p2,regression
console.log(mobile.workspace === web.workspace); // true

const scratch = new Board("Scratch", acme, [new Column("Todo", 4)], []);
const leaky = scratch.shallowCopy();
leaky.columns[0].wipLimit = 9;
console.log(scratch.columns[0].wipLimit); // 9, the original changed

When to use it

Situations where it pays off.

  • Your code must create copies of objects whose concrete class it does not know, such as boards that may be built-in templates or customer-made ones.

    clone() is polymorphic. The caller only sees the Prototype interface, and each class copies itself correctly, so no switch over types or constructor knowledge leaks into the client.

  • Configuring an object is expensive or long, for example it needs several lookups, a parsed config file or many setup calls.

    You pay the setup cost once for the prototype, then each new instance is a copy. Copying in-memory data is usually far cheaper than repeating I/O or validation.

  • You have many subclasses that differ only in their initial state, like BugTriageBoard, HiringBoard and ContentBoard each just presetting columns.

    Replace the subclasses with configured instances of one class stored in a registry. New variants become data, not code, and can even be created at runtime by users.

  • You need a snapshot or a scratch copy that can be modified without affecting the original, such as a preview of edits before saving.

    A correct deep clone gives you an independent object to experiment on, which you can discard or commit later.

How to implement it

Steps to introduce it in existing code.

  1. Define a Prototype interface with a single clone() method, or use your language's built-in hook (__clone in PHP, __copy__/__deepcopy__ in Python) if it fits your copy rules.

  2. For each class, list its fields and classify them: primitives and immutable values copy as-is, owned mutable objects and collections need a deep copy, and shared collaborators (workspaces, services, connections) keep the same reference.

  3. Implement clone() to build a new instance, delegating to the clone() of each owned child object rather than copying its fields from the outside.

  4. Copy collections into new collections. A new array containing the same element objects is still shallow for those elements.

  5. Add a registry that stores configured prototypes by key and returns clones, never the stored instance itself.

  6. Write tests that mutate a clone (nested fields included) and assert the prototype did not change, and that shared references are still identical.

Pros and cons

What you gain and what you pay.

Pros

  • Clients create objects without depending on concrete classes or construction steps.
  • Expensive configuration is done once; new instances come from cheap in-memory copies.
  • Variants become data: customers or admins can register new templates at runtime without new subclasses or deploys.
  • Copy rules live next to the fields they protect, so each class stays responsible for its own correct duplication.

Cons

  • Every class in the object graph needs a correct clone; one missed nested collection reintroduces shared-state bugs that are hard to trace.
  • Circular references and objects holding external resources (sockets, file handles, locks) are awkward or impossible to clone safely.
  • Deciding deep versus shared per field is a real design decision, and generic deep-copy utilities can get it wrong by copying things that must stay shared.
  • Deep copies of large graphs cost time and memory proportional to the size of the graph, which matters if you clone often.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

What is the difference between a shallow copy and a deep copy?

A shallow copy creates a new top-level object but copies each field as-is, so reference fields still point to the same nested objects. A deep copy also copies those nested objects, recursively, so the result shares no mutable state with the original. In practice you rarely want either extreme: Larkspur's Board deep-copies columns and labels but deliberately shares its Workspace.

Why not just use copy.deepcopy, structuredClone or PHP's clone everywhere?

Generic tools apply one rule to every field. copy.deepcopy and structuredClone would duplicate the Workspace too, and structuredClone drops class prototypes so you get plain objects without methods. PHP's clone is shallow for nested objects unless you write __clone. Use them as building blocks inside a clone() method that encodes your actual ownership rules.

How do you handle circular references when cloning?

Keep a map from original objects to their copies during a single clone operation. Before copying a node, check the map and return the existing copy if there is one. Python's copy.deepcopy does this with its memo dictionary. Without it, a cycle causes infinite recursion.

When is Prototype the wrong choice?

When objects are cheap to construct and you always know the concrete class, a constructor or factory is simpler. It is also a poor fit for objects that wrap live resources such as database connections or open files, because there is no meaningful way to copy them. And if your objects are immutable, you can share them freely and do not need copies at all.

How would you test a clone() implementation in an interview?

Clone the prototype, mutate every level of the copy, including nested objects and collections, then assert the prototype is unchanged. Also assert identity for fields that should be shared, like copy.workspace === original.workspace. A test that only checks top-level fields will miss the exact bug that shallow copies cause.

Next guide5 of 5 · Creational patternsSingleton: One Shared Instance, and Why You Usually Want DI InsteadRead the next one