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.
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 unaffectedThe 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 changedfrom __future__ import annotations
from typing import Optional, Protocol, TypeVar
T = TypeVar("T", covariant=True)
class Prototype(Protocol[T]):
def clone(self) -> T: ...
class Workspace:
def __init__(self, id: str, name: str) -> None:
self.id = id
self.name = name
class Column:
def __init__(self, title: str, wip_limit: Optional[int]) -> None:
self.title = title
self.wip_limit = wip_limit
def clone(self) -> Column:
return Column(self.title, self.wip_limit)
class Board:
def __init__(
self,
name: str,
workspace: Workspace,
columns: list[Column],
labels: list[str],
) -> None:
self.name = name
self.workspace = workspace
self.columns = columns
self.labels = labels
def clone(self) -> Board:
return Board(
self.name,
self.workspace, # shared on purpose: never duplicate a tenant
[column.clone() for column in self.columns],
list(self.labels),
)
# The buggy version from the first Duplicate button, kept for comparison.
def shallow_copy(self) -> Board:
return Board(self.name, self.workspace, self.columns, self.labels)
class TemplateRegistry:
def __init__(self) -> None:
self._templates: dict[str, Board] = {}
def register(self, key: str, board: Board) -> None:
self._templates[key] = board
def create(self, key: str, name: str) -> Board:
template = self._templates.get(key)
if template is None:
raise KeyError(f"Unknown template: {key}")
board = template.clone()
board.name = name
return board
acme = Workspace("ws-17", "Acme Support")
registry = TemplateRegistry()
registry.register(
"bug-triage",
Board(
"Bug triage",
acme,
[Column("New", None), Column("Investigating", 5), Column("Fixed", None)],
["p1", "p2", "regression"],
),
)
mobile = registry.create("bug-triage", "Mobile bugs")
mobile.columns[1].wip_limit = 3
mobile.labels.append("ios")
web = registry.create("bug-triage", "Web bugs")
print(web.columns[1].wip_limit) # 5
print(",".join(web.labels)) # p1,p2,regression
print(mobile.workspace is web.workspace) # True
scratch = Board("Scratch", acme, [Column("Todo", 4)], [])
leaky = scratch.shallow_copy()
leaky.columns[0].wip_limit = 9
print(scratch.columns[0].wip_limit) # 9, the original changed<?php
declare(strict_types=1);
interface Prototype
{
public function clone(): static;
}
final class Workspace
{
public function __construct(
public readonly string $id,
public readonly string $name,
) {}
}
final class Column implements Prototype
{
public function __construct(
public string $title,
public ?int $wipLimit,
) {}
public function clone(): static
{
return clone $this;
}
}
final class Board implements Prototype
{
/**
* @param Column[] $columns
* @param string[] $labels
*/
public function __construct(
public string $name,
public readonly Workspace $workspace,
public array $columns,
public array $labels,
) {}
public function clone(): static
{
return clone $this;
}
// PHP's clone copies properties shallowly; arrays are copied by value,
// but the Column objects inside them are still shared handles.
public function __clone(): void
{
$this->columns = array_map(fn (Column $column) => $column->clone(), $this->columns);
// $this->workspace stays shared on purpose: never duplicate a tenant.
}
// The buggy version from the first Duplicate button, kept for comparison.
public function shallowCopy(): Board
{
return new Board($this->name, $this->workspace, $this->columns, $this->labels);
}
}
final class TemplateRegistry
{
/** @var array<string, Board> */
private array $templates = [];
public function register(string $key, Board $board): void
{
$this->templates[$key] = $board;
}
public function create(string $key, string $name): Board
{
if (!isset($this->templates[$key])) {
throw new InvalidArgumentException("Unknown template: {$key}");
}
$board = $this->templates[$key]->clone();
$board->name = $name;
return $board;
}
}
$acme = new Workspace('ws-17', 'Acme Support');
$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'],
),
);
$mobile = $registry->create('bug-triage', 'Mobile bugs');
$mobile->columns[1]->wipLimit = 3;
$mobile->labels[] = 'ios';
$web = $registry->create('bug-triage', 'Web bugs');
echo $web->columns[1]->wipLimit, PHP_EOL; // 5
echo implode(',', $web->labels), PHP_EOL; // p1,p2,regression
var_dump($mobile->workspace === $web->workspace); // bool(true)
$scratch = new Board('Scratch', $acme, [new Column('Todo', 4)], []);
$leaky = $scratch->shallowCopy();
$leaky->columns[0]->wipLimit = 9;
echo $scratch->columns[0]->wipLimit, PHP_EOL; // 9, the original changedWhen 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.
Define a Prototype interface with a single
clone()method, or use your language's built-in hook (__clonein PHP,__copy__/__deepcopy__in Python) if it fits your copy rules.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.
Implement
clone()to build a new instance, delegating to theclone()of each owned child object rather than copying its fields from the outside.Copy collections into new collections. A new array containing the same element objects is still shallow for those elements.
Add a registry that stores configured prototypes by key and returns clones, never the stored instance itself.
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.
- Factory Method: Let Subclasses Decide Which Object to Create
Factory Method creates objects through subclass overrides; Prototype creates them by copying an instance. Prototype avoids a parallel hierarchy of creator classes but needs every product to support cloning.
- Abstract Factory: Create Families of Objects That Belong Together
An Abstract Factory can be implemented by holding a set of prototypes and cloning them, which lets you configure a product family at runtime instead of subclassing the factory.
- Builder Pattern: Assemble Complex Objects Step by Step
Builder assembles a complex object step by step. You can build one configured instance with a Builder, register it as a prototype, and clone it from then on.
- Memento Pattern: Save and Restore State Without Exposing It
A deep clone is a simple way to capture state for a Memento when the object has no external resources and its graph is reasonably small.
- Composite Pattern: Treat Single Items and Groups Through One Interface
Cloning a Composite means recursively cloning its children, exactly as Board delegates to Column.clone. Prototype is a common way to duplicate whole trees.
- Repeated Switches: the same type-code switch scattered across a codebase
A switch over template types that constructs each object by hand is a classic trigger for introducing a prototype registry.
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.