Patterncore
Prototype pattern
Also called Prototype, clone, prototypical instance.
A program makes new objects by copying a configured example object, the prototype, and not by calling a constructor of a known class. Each class decides how deep its own copy goes.
- Family
- creational-design
- Intent
- Make new objects by copying a prototypical instance, so that the code that makes them does not name their classes.
- Also called
- clone
Intent
Make new objects by copying a prototypical instance. The code that asks for a new object does not name its class. It holds an object of the right kind, and it asks that object for a copy.1
Problem
Design Patterns starts from a framework for graphical editors. An editor of music scores is built on it. The palette of the editor has a tool for each kind of note and for a staff. The framework owns the tool class, but it does not know the classes of notes and staves, because the music editor defines them later.1 One answer is a subclass of the tool for each kind of object, where each subclass calls one constructor. The number of tool classes then grows with the number of object classes.
The same need appears in other places. A level editor of a game has a goblin, an orc and a spike trap, each with its own health, damage and items. A game designer adds a kind of monster from data at run time, not from a class in the code. A plugin adds a class that the main program never saw. A document template holds a styled table that the user wants to insert many times.
The forces are these. The code that makes objects must not depend on their concrete classes. The program must add kinds at run time, often as other values of the same class. And the configuration of a kind can be costly to build, so the program wants to build it once and then copy it.
Solution
Design Patterns names three participants.1
- Prototype declares an operation that copies the object. It is often called
cloneorcopy. - ConcretePrototype implements the copy for its own class.
- Client makes a new object by asking a prototype to copy itself.
A prototype manager (a registry) often holds the prototypes by key. The client asks the registry for a key, and the registry returns a copy of the prototype for that key.1
Client ---> Registry: spawn("goblin")
prototypes: map of key to Prototype
spawn(key) = prototypes[key].clone()
|
Prototype (interface)
clone(), describe()
^ ^
| |
Monster Trap
clone: deep copy clone: shallow copy
of the items list (all fields immutable)
The registry depends only on the interface. To add a kind, the program registers a configured object. Design Patterns describes this as a way to specify objects by varying values: a goblin and an orc can be two objects of one class, with different values, and no subclass.1
Shallow and deep copies
The pattern is only as correct as the copy. A shallow copy makes a new object and fills each field with the value of the old field. When the field holds a reference, the copy holds the same reference, so the two objects share the referred object. A deep copy makes a new object and copies the referred objects as well, recursively.2 Java's Object.clone and .NET's MemberwiseClone are shallow by definition.312 So are a Go struct assignment, slices.Clone, Object.assign in JavaScript, and a C# with expression.1514
This program clones the goblin with a shallow copy. The prototype and every clone share one list:
This code runs but gives a wrong answer on purpose.
import copy
class Monster:
def __init__(self, name, items):
self.name = name
self.items = items
def clone(self):
return copy.copy(self) # shallow: the clone shares self.items
goblin = Monster("goblin", ["dagger"])
first = goblin.clone()
first.items.append("torch")
second = goblin.clone()
print("first:", first.items)
print("second:", second.items)
print("prototype:", goblin.items)
first: ['dagger', 'torch']
second: ['dagger', 'torch']
prototype: ['dagger', 'torch']
The torch went into the prototype, so every later goblin gets it. The fix is copy.deepcopy, or a clone that copies the list, as the Python example does.
In Go the same bug can hide better. A struct copy copies the slice header, and the header points to the prototype's array. When that array has spare capacity, append writes into it and does not allocate. Each clone then writes its next item into the same slot:
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
type Monster struct {
Name string
Items []string
}
func (m *Monster) Clone() *Monster {
copy := *m // the copy shares the array behind Items
return ©
}
func main() {
items := make([]string, 1, 4)
items[0] = "dagger"
goblin := &Monster{Name: "goblin", Items: items}
first := goblin.Clone()
first.Items = append(first.Items, "torch")
second := goblin.Clone()
second.Items = append(second.Items, "shield")
fmt.Println("first:", first.Items)
fmt.Println("second:", second.Items)
fmt.Println("prototype:", goblin.Items)
}
first: [dagger shield]
second: [dagger shield]
prototype: [dagger]
The prototype looks correct, because its length is still 1. The first goblin lost its torch to the shield of the second. The Go example calls slices.Clone in Clone to give each copy its own array.15
A deep copy is not always right either. The Python documentation names two problems: a recursive structure can make the copy loop for ever, and a deep copy can copy data that was meant to be shared between copies.2 copy.deepcopy keeps a memo of the objects that it has already copied, which solves the first problem. A class solves the second with __deepcopy__, which copies only the fields that must not be shared. A monster can own its items and share its sprite image with all other goblins. So the right copy is a decision for each field, and the class that owns the fields makes it.
Java's clone and its problems
Java builds a form of the pattern into Object. Object.clone makes an object of the same class and copies each field "as if by assignment", which is a shallow copy. It throws CloneNotSupportedException unless the class implements Cloneable.3 Cloneable has no methods. It only changes the behaviour of a protected method in Object, so a class that implements Cloneable still has no public clone. The API says that a call to clone on an object that implements Cloneable is not sure to succeed, even by reflection.4
Bloch lists more problems. clone makes the object with no constructor call. A clone that needs a deep copy must assign the copied field after super.clone(), so the field cannot be final. And the checked exception forces a try block on code that cannot fail.5 The compiler shows the final problem:
This code does not compile, on purpose.
import java.util.ArrayList;
import java.util.List;
public class Main {
static class Monster implements Cloneable {
final List<String> items = new ArrayList<>();
@Override
public Monster clone() {
try {
Monster copy = (Monster) super.clone();
copy.items = new ArrayList<>(items); // a final field cannot be assigned here
return copy;
} catch (CloneNotSupportedException error) {
throw new AssertionError(error);
}
}
}
public static void main(String[] args) {
System.out.println(new Monster().clone().items);
}
}
Bloch recommends a copy constructor or a static copy factory instead: a constructor that takes an object of its own class.5 The Java example uses a copy constructor behind a copy method of an interface. A copy constructor alone does not give the pattern. The caller must name the class to call it, so a copy method that calls the constructor is still needed when the caller holds only the interface.
Copy constructors and slicing in C++
In C++, every class has a copy constructor, and the compiler writes one that copies each member. Members such as std::vector and std::string copy their elements, so the default is often a deep copy of the data. A raw pointer member is copied as an address. The copy constructor is not virtual: a copy of a Monster through a reference to its base class makes a base object, and the derived part is lost. This is slicing:
This code runs but gives a wrong answer on purpose.
#include <iostream>
#include <string>
#include <vector>
struct Thing {
virtual ~Thing() = default;
virtual std::string describe() const { return "a thing"; }
};
struct Monster : Thing {
std::string describe() const override { return "a goblin with a dagger"; }
};
int main() {
Monster goblin;
const Thing& prototype = goblin;
std::vector<Thing> copies{prototype, prototype}; // copies only the Thing part
for (const auto& copy : copies) {
std::cout << copy.describe() << '\n';
}
}
a thing
a thing
The C++ Core Guidelines give the fix: a polymorphic class makes its copy operations protected or deleted, and it gives a virtual clone that returns an owning pointer to a copy of the most derived type.1819 The C++ example does this.
Prototypes in JavaScript
JavaScript has prototypes in the language. Each object has a link to a prototype object, and a property read that does not find an own property follows the link.9 Object.create(p) makes an object whose prototype is p.8 The design comes from prototype-based languages. In Self, there are no classes. Any object can be cloned, and a new object is made by copying a prototype.10 Lieberman described how prototypical objects can share behaviour, with delegation in place of class inheritance.11
A JavaScript prototype is not a copy. The new object delegates to the prototype. It reads the inherited fields from it until it writes its own. A write of a field makes an own property, but a change inside an inherited array is not a write of the field:
This code runs but gives a wrong answer on purpose.
const goblin = { name: "goblin", items: ["dagger"] };
const first = Object.create(goblin);
first.items.push("torch"); // reads goblin.items, then changes that array
const second = Object.create(goblin);
console.log("second:", second.items.join(", "));
console.log("prototype:", goblin.items.join(", "));
console.log("first has its own items:", Object.hasOwn(first, "items"));
second: dagger, torch
prototype: dagger, torch
first has its own items: false
structuredClone makes a deep copy, and it handles cycles. It throws a DataCloneError for a value that it cannot serialize, such as a function.67 It does not walk or copy the prototype chain, and it does not copy private class fields.7 So a clone of a class instance is a plain object with no methods:
This code raises TypeError, on purpose.
class Monster {
constructor(name, items) {
this.name = name;
this.items = items;
}
describe() {
return `${this.name}: ${this.items.join(", ")}`;
}
}
const copy = structuredClone(new Monster("goblin", ["dagger"]));
console.log(Object.getPrototypeOf(copy) === Object.prototype);
console.log(copy.describe());
Use structuredClone for plain data, such as a configuration or a message. For objects with behaviour, write a clone method, as the JavaScript and TypeScript examples do.
Clone and trait objects in Rust
Rust's Clone is explicit, and #[derive(Clone)] clones each field. For owned data, such as Vec<String>, this is a deep copy. A field of type Rc<T> or Arc<T> clones the pointer, so the clone shares the value.16 A registry of prototypes needs trait objects, and Clone cannot be a supertrait of a trait used as dyn. Clone requires Sized, and a trait with Sized as a supertrait is not dyn compatible [items.traits.dyn-compatible.sized].17 The compiler reports error E0038.
This code does not compile, on purpose.
trait Prototype: Clone {
fn describe(&self) -> String;
}
#[derive(Clone)]
struct Trap {
damage: u32,
}
impl Prototype for Trap {
fn describe(&self) -> String {
format!("trap: damage {}", self.damage)
}
}
fn main() {
let prototype: Box<dyn Prototype> = Box::new(Trap { damage: 5 });
println!("{}", prototype.describe());
}
The Rust example adds a method clone_box that returns Box<dyn Prototype>. Each type implements it with its own clone.
Example
Each example file builds the same registry. It has a goblin prototype, a monster with health 30 and a dagger, and a spike trap prototype with damage 5. The program spawns two goblins and a trap, gives the first goblin a torch, and prints all three and the prototype. The prototype must still have only the dagger.
| Language | Form |
|---|---|
| Python | a clone method that calls copy.deepcopy or copy.copy |
| JavaScript | Object.create on the prototype, with a copy of each array |
| TypeScript | an interface with clone(): this |
| Java | an interface with copy, implemented by a copy constructor |
| C# | MemberwiseClone and a copy of the list; a record with with |
| Go | a struct copy and slices.Clone |
| Rust | #[derive(Clone)] and a clone_box method for trait objects |
| C++ | a virtual clone that returns std::unique_ptr and uses the copy constructor |
import copy
class Monster:
def __init__(self, name, health, items):
self.name = name
self.health = health
self.items = items
def clone(self):
# A deep copy: the clone gets its own list of items.
return copy.deepcopy(self)
def describe(self):
return f"{self.name}: health {self.health}, items {', '.join(self.items)}"
class Trap:
def __init__(self, name, damage):
self.name = name
self.damage = damage
def clone(self):
# Every field is immutable, so a shallow copy is enough.
return copy.copy(self)
def describe(self):
return f"{self.name}: damage {self.damage}"
class Registry:
def __init__(self):
self._prototypes = {}
def add(self, key, prototype):
self._prototypes[key] = prototype
def get(self, key):
return self._prototypes[key]
def spawn(self, key):
return self._prototypes[key].clone()
registry = Registry()
registry.add("goblin", Monster("goblin", 30, ["dagger"]))
registry.add("spikes", Trap("spikes", 5))
first = registry.spawn("goblin")
first.items.append("torch")
second = registry.spawn("goblin")
trap = registry.spawn("spikes")
for thing in [first, second, trap]:
print(thing.describe())
print("prototype", registry.get("goblin").describe())
goblin: health 30, items dagger, torch
goblin: health 30, items dagger
spikes: damage 5
prototype goblin: health 30, items dagger
- Verdict: stdlib.
copy.copymakes a shallow copy andcopy.deepcopymakes a deep copy of any object whose class does not forbid it. A class can change the result with__copy__and__deepcopy__. - The registry calls
cloneand does not know the class of the object that it copies. Each class decides how deep its own copy goes. deepcopykeeps a memo of the objects that it has already copied, so a cycle of references or a shared object appears once in the copy, as in the original.- A frozen
dataclasswithdataclasses.replacemakes a copy with some fields changed, which covers many uses of a prototype with no clone method.
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
class Prototype {
public:
virtual ~Prototype() = default;
virtual std::unique_ptr<Prototype> clone() const = 0;
virtual std::string describe() const = 0;
protected:
Prototype() = default;
Prototype(const Prototype&) = default; // protected, so no caller can slice a copy
Prototype& operator=(const Prototype&) = default;
};
class Monster : public Prototype {
public:
Monster(std::string name, int health, std::vector<std::string> items)
: name_(std::move(name)), health_(health), items_(std::move(items)) {}
// The copy constructor that the compiler writes copies the vector and its strings.
std::unique_ptr<Prototype> clone() const override { return std::make_unique<Monster>(*this); }
std::string describe() const override {
std::string text = name_ + ": health " + std::to_string(health_) + ", items ";
for (std::size_t i = 0; i < items_.size(); ++i) {
text += (i > 0 ? ", " : "") + items_[i];
}
return text;
}
void add_item(std::string item) { items_.push_back(std::move(item)); }
private:
std::string name_;
int health_;
std::vector<std::string> items_;
};
class Trap : public Prototype {
public:
Trap(std::string name, int damage) : name_(std::move(name)), damage_(damage) {}
std::unique_ptr<Prototype> clone() const override { return std::make_unique<Trap>(*this); }
std::string describe() const override { return name_ + ": damage " + std::to_string(damage_); }
private:
std::string name_;
int damage_;
};
int main() {
std::map<std::string, std::unique_ptr<Prototype>> registry;
registry["goblin"] = std::make_unique<Monster>("goblin", 30, std::vector<std::string>{"dagger"});
registry["spikes"] = std::make_unique<Trap>("spikes", 5);
auto spawn = [&](const std::string& key) { return registry.at(key)->clone(); };
auto first = spawn("goblin");
dynamic_cast<Monster&>(*first).add_item("torch");
auto second = spawn("goblin");
auto trap = spawn("spikes");
for (const auto* thing : {first.get(), second.get(), trap.get()}) {
std::cout << thing->describe() << '\n';
}
std::cout << "prototype " << registry.at("goblin")->describe() << '\n';
}
goblin: health 30, items dagger, torch
goblin: health 30, items dagger
spikes: damage 5
prototype goblin: health 30, items dagger
- Verdict: idiom. A virtual
clonethat returnsstd::unique_ptrto the base class. Each class implements it with its own copy constructor, so the copy has the most derived type. - A
std::vectorand astd::stringare values: the copy constructor copies their elements. A raw pointer member is copied as an address, so a class with one needs its own copy constructor. - The base class makes its copy constructor
protected. A public one would let a caller copy aMonsterinto aPrototypeby value and lose the derived part, which is slicing. The C++ Core Guidelines give this rule and the virtualcloneas the fix.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Main {
interface Prototype {
Prototype copy();
String describe();
}
static final class Monster implements Prototype {
final String name;
final int health;
final List<String> items;
Monster(String name, int health, List<String> items) {
this.name = name;
this.health = health;
this.items = new ArrayList<>(items);
}
// A copy constructor: it copies the list, so the copy has its own items.
Monster(Monster other) {
this(other.name, other.health, other.items);
}
@Override
public Monster copy() {
return new Monster(this);
}
@Override
public String describe() {
return name + ": health " + health + ", items " + String.join(", ", items);
}
}
record Trap(String name, int damage) implements Prototype {
// A record is immutable here, so the copy can be the same object.
@Override
public Trap copy() {
return this;
}
@Override
public String describe() {
return name + ": damage " + damage;
}
}
static final Map<String, Prototype> registry = new LinkedHashMap<>();
static Prototype spawn(String key) {
return registry.get(key).copy();
}
public static void main(String[] args) {
registry.put("goblin", new Monster("goblin", 30, List.of("dagger")));
registry.put("spikes", new Trap("spikes", 5));
Monster first = (Monster) spawn("goblin");
first.items.add("torch");
Prototype second = spawn("goblin");
Prototype trap = spawn("spikes");
for (Prototype thing : List.of(first, second, trap)) {
System.out.println(thing.describe());
}
System.out.println("prototype " + registry.get("goblin").describe());
}
}
goblin: health 30, items dagger, torch
goblin: health 30, items dagger
spikes: damage 5
prototype goblin: health 30, items dagger
- Verdict: idiom. An interface with a
copymethod, implemented with a copy constructor. The return type ofcopyinMonsterisMonster, a covariant return type, so a caller that knows the class needs no cast. - The program does not use
Object.clone.cloneisprotectedinObject, theCloneableinterface has no methods, andObject.clonemakes a shallow copy that skips the constructors. The node page shows why afinalfield that needs a deep copy cannot work withclone. Trapis a record whose components are immutable, so it returns itself. An immutable prototype needs no copy at all.- Arrays implement
Cloneable, andarray.clone()returns an array of the same type. It is shallow: an array of arrays shares the inner arrays.
var registry = new Dictionary<string, IPrototype>
{
["goblin"] = new Monster("goblin", 30, ["dagger"]),
["spikes"] = new Trap("spikes", 5),
};
IPrototype Spawn(string key) => registry[key].Copy();
var first = (Monster)Spawn("goblin");
first.Items.Add("torch");
var second = Spawn("goblin");
var trap = Spawn("spikes");
foreach (var thing in new[] { first, second, trap })
{
Console.WriteLine(thing.Describe());
}
Console.WriteLine("prototype " + registry["goblin"].Describe());
var bigger = (Trap)trap with { Damage = 9 };
Console.WriteLine($"with: {bigger.Describe()}, original: {trap.Describe()}");
interface IPrototype
{
IPrototype Copy();
string Describe();
}
class Monster(string name, int health, List<string> items) : IPrototype
{
public string Name { get; } = name;
public int Health { get; } = health;
public List<string> Items { get; private set; } = items;
public IPrototype Copy()
{
// MemberwiseClone copies the fields; the list is a reference, so copy it too.
var copy = (Monster)MemberwiseClone();
copy.Items = [.. Items];
return copy;
}
public string Describe() => $"{Name}: health {Health}, items {string.Join(", ", Items)}";
}
record Trap(string Name, int Damage) : IPrototype
{
public IPrototype Copy() => this with { };
public string Describe() => $"{Name}: damage {Damage}";
}
goblin: health 30, items dagger, torch
goblin: health 30, items dagger
spikes: damage 5
prototype goblin: health 30, items dagger
with: spikes: damage 9, original: spikes: damage 5
- Verdict: stdlib.
Object.MemberwiseCloneis aprotectedmethod that makes a shallow copy: it copies each field, and a field of a reference type keeps the same object. The class then copies the fields that must not be shared. - A record supports the
withexpression, which makes a copy with some members changed. The copy is shallow, asMemberwiseCloneis. - The interface method is
Copy, notClone. The C# compiler rejects a member namedClonein a record with error CS8859, because the compiler makes its own clone method forwith. - The program defines its own interface. Microsoft recommends that public APIs do not implement
ICloneable, because the interface does not say whetherCloneis deep or shallow.
const monster = {
describe() {
return `${this.name}: health ${this.health}, items ${this.items.join(", ")}`;
},
};
const trap = {
describe() {
return `${this.name}: damage ${this.damage}`;
},
};
// The prototypes are objects whose prototype is monster or trap.
const goblin = Object.assign(Object.create(monster), {
name: "goblin",
health: 30,
items: ["dagger"],
});
const spikes = Object.assign(Object.create(trap), { name: "spikes", damage: 5 });
const registry = new Map([
["goblin", goblin],
["spikes", spikes],
]);
function spawn(key) {
const prototype = registry.get(key);
// The new object delegates to the prototype. It gets its own copy of each array.
const thing = Object.create(prototype);
for (const [field, value] of Object.entries(prototype)) {
if (Array.isArray(value)) thing[field] = [...value];
}
return thing;
}
const first = spawn("goblin");
first.items.push("torch");
const second = spawn("goblin");
const third = spawn("spikes");
for (const thing of [first, second, third]) {
console.log(thing.describe());
}
console.log("prototype", registry.get("goblin").describe());
console.log("own fields of second:", Object.keys(second).join(", "));
goblin: health 30, items dagger, torch
goblin: health 30, items dagger
spikes: damage 5
prototype goblin: health 30, items dagger
own fields of second: items
- Verdict: native. Each object has an internal link to a prototype object.
Object.create(p)makes an object whose prototype isp, and a property read that does not find an own property follows the chain top. - A clone made with
Object.createcopies nothing. It delegates to the prototype, so a later change togoblin.healthwould show in every goblin that has not set its ownhealth. The last line shows thatsecondhas only one own field. - A write makes an own property on the new object. A change inside an inherited array is not a write to the new object, so
spawngives each object its own copy of each array. The node page shows the bug without that loop. structuredClonemakes a deep copy of plain data, but it does not keep the prototype of the object. It is a copy of data, not a clone of an object with behaviour.
interface Prototype {
clone(): this;
describe(): string;
}
class Monster implements Prototype {
name: string;
health: number;
items: string[];
constructor(name: string, health: number, items: string[]) {
this.name = name;
this.health = health;
this.items = items;
}
clone(): this {
// Keep the class of this object, copy the fields, then copy the array.
const copy = Object.assign(Object.create(Object.getPrototypeOf(this)), this) as this;
copy.items = [...this.items];
return copy;
}
describe(): string {
return `${this.name}: health ${this.health}, items ${this.items.join(", ")}`;
}
}
class Trap implements Prototype {
name: string;
damage: number;
constructor(name: string, damage: number) {
this.name = name;
this.damage = damage;
}
clone(): this {
return Object.assign(Object.create(Object.getPrototypeOf(this)), this) as this;
}
describe(): string {
return `${this.name}: damage ${this.damage}`;
}
}
class Registry {
private readonly prototypes = new Map<string, Prototype>();
add(key: string, prototype: Prototype): void {
this.prototypes.set(key, prototype);
}
get(key: string): Prototype {
const prototype = this.prototypes.get(key);
if (prototype === undefined) throw new Error(`no prototype ${key}`);
return prototype;
}
spawn(key: string): Prototype {
return this.get(key).clone();
}
}
const registry = new Registry();
registry.add("goblin", new Monster("goblin", 30, ["dagger"]));
registry.add("spikes", new Trap("spikes", 5));
const first = registry.spawn("goblin");
if (first instanceof Monster) first.items.push("torch");
const second = registry.spawn("goblin");
const trap = registry.spawn("spikes");
for (const thing of [first, second, trap]) {
console.log(thing.describe());
}
console.log("prototype", registry.get("goblin").describe());
console.log("the clone is a Monster:", first instanceof Monster);
goblin: health 30, items dagger, torch
goblin: health 30, items dagger
spikes: damage 5
prototype goblin: health 30, items dagger
the clone is a Monster: true
- Verdict: idiom. An interface with
clone(): this. The polymorphicthistype says that a clone has the type of the object it copies, somonster.clone()has the static typeMonsterwhenmonsterhas that type. Object.create(Object.getPrototypeOf(this))keeps the class: the copy is an instance ofMonster.Object.assigncopies the own fields, which is a shallow copy, so the method copies the array by hand.- A class with
#privatefields cannot useObject.assignfor its clone, because private fields are not properties. Such a class calls its own constructor inclone. structuredClonegives a deep copy of the data, but the result is a plain object with no methods.
package main
import (
"fmt"
"slices"
"strings"
)
type Prototype interface {
Clone() Prototype
Describe() string
}
type Monster struct {
Name string
Health int
Items []string
}
func (m *Monster) Clone() Prototype {
copy := *m // copies the fields; Items still shares its array
copy.Items = slices.Clone(m.Items) // gives the copy its own array
return ©
}
func (m *Monster) Describe() string {
return fmt.Sprintf("%s: health %d, items %s", m.Name, m.Health, strings.Join(m.Items, ", "))
}
type Trap struct {
Name string
Damage int
}
func (t *Trap) Clone() Prototype {
copy := *t // no field refers to shared data, so this copy is enough
return ©
}
func (t *Trap) Describe() string {
return fmt.Sprintf("%s: damage %d", t.Name, t.Damage)
}
func main() {
registry := map[string]Prototype{
"goblin": &Monster{Name: "goblin", Health: 30, Items: []string{"dagger"}},
"spikes": &Trap{Name: "spikes", Damage: 5},
}
spawn := func(key string) Prototype { return registry[key].Clone() }
first := spawn("goblin").(*Monster)
first.Items = append(first.Items, "torch")
second := spawn("goblin")
trap := spawn("spikes")
for _, thing := range []Prototype{first, second, trap} {
fmt.Println(thing.Describe())
}
fmt.Println("prototype", registry["goblin"].Describe())
}
goblin: health 30, items dagger, torch
goblin: health 30, items dagger
spikes: damage 5
prototype goblin: health 30, items dagger
- Verdict: idiom. An interface with a
Clonemethod. The assignmentcopy := *mcopies a struct by value, field by field. - A slice is a small header with a pointer to an array, and a map value refers to a hash table. A struct copy copies the header and the reference, not the elements, so the method calls
slices.Clone.slices.Cloneandmaps.Cloneare shallow: they copy the elements by assignment. - The node page shows the bug when
Cloneomitsslices.Cloneand a laterappendwrites into the shared array. - Go has no copy constructors and no
clonein the language. Each type that holds a slice, a map or a pointer must write its own copy.
use std::collections::BTreeMap;
trait Prototype {
fn clone_box(&self) -> Box<dyn Prototype>;
fn describe(&self) -> String;
fn add_item(&mut self, _item: &str) {}
}
#[derive(Clone)]
struct Monster {
name: String,
health: u32,
items: Vec<String>,
}
#[derive(Clone)]
struct Trap {
name: String,
damage: u32,
}
impl Prototype for Monster {
fn clone_box(&self) -> Box<dyn Prototype> {
Box::new(self.clone()) // the derived Clone clones the Vec and each String
}
fn describe(&self) -> String {
format!("{}: health {}, items {}", self.name, self.health, self.items.join(", "))
}
fn add_item(&mut self, item: &str) {
self.items.push(item.to_string());
}
}
impl Prototype for Trap {
fn clone_box(&self) -> Box<dyn Prototype> {
Box::new(self.clone())
}
fn describe(&self) -> String {
format!("{}: damage {}", self.name, self.damage)
}
}
fn main() {
let mut registry: BTreeMap<&str, Box<dyn Prototype>> = BTreeMap::new();
registry.insert(
"goblin",
Box::new(Monster { name: "goblin".into(), health: 30, items: vec!["dagger".into()] }),
);
registry.insert("spikes", Box::new(Trap { name: "spikes".into(), damage: 5 }));
let spawn = |key: &str| registry[key].clone_box();
let mut first = spawn("goblin");
first.add_item("torch");
let second = spawn("goblin");
let trap = spawn("spikes");
for thing in [&first, &second, &trap] {
println!("{}", thing.describe());
}
println!("prototype {}", registry["goblin"].describe());
}
goblin: health 30, items dagger, torch
goblin: health 30, items dagger
spikes: damage 5
prototype goblin: health 30, items dagger
- Verdict: native for values, idiom for trait objects.
#[derive(Clone)]writes aclonethat clones each field, andVec<String>clones its elements, so the copy owns all its data. Clonecannot be a supertrait of a trait that is used asdyn Prototype.ClonerequiresSized, and a trait withSizedas a supertrait is not dyn compatible. Theclone_boxmethod returns aBox<dyn Prototype>instead. The node page shows the compile error.- A deep copy is the default only for owned data. A field of type
Rc<T>orArc<T>clones the pointer and shares the value, so a derivedCloneon such a struct shares that state with the original. - The borrow checker stops the shared-list bug of other languages: two owners cannot both change one
VecwithoutRefCellor a lock.
Consequences
Design Patterns lists these benefits.1 The client does not know the concrete classes, as with Abstract Factory and Builder. A program can add and remove kinds at run time by registering prototypes. It can define kinds by changing values, and by changing structure when the prototype is a composite. It needs fewer subclasses than Factory Method, which needs a creator class for each product class. And a program can configure itself with classes that it loads at run time.
The main liability is that each class must implement its copy. Design Patterns says that this can be hard for a class that already exists, and for a class whose internals hold objects that do not support copying or that have circular references.1 Each field added to the class is a decision: share it or copy it. A field added later with the wrong decision is a bug that no type checker finds.
A clone also skips the constructor in some languages. Object.clone, MemberwiseClone and a struct copy do not run the code that checks the invariants of the object or registers it somewhere. A class that counts its instances, opens a file or subscribes to an event in its constructor must repeat that work in its copy. Design Patterns notes that a clone often needs a separate operation to initialize its state after the copy.1
When not to use it
Do not write a clone method for objects whose fields are all immutable. The object itself can be the prototype and the copy. The Java and C# examples return the same Trap or a with copy for this reason. A Python frozen dataclass with dataclasses.replace makes a variant with some fields changed.20
Do not use the pattern when the set of classes is fixed and known where the objects are made. A constructor call, a factory function, or a map from a key to a constructor function is shorter, and it runs the constructor's checks. In languages with first-class functions and classes, a registry of factory functions does what a registry of prototypes does. It needs no copy code. See Factory Method pattern.
Do not use structuredClone, copy.deepcopy or serialization to clone objects with behaviour or with identity, such as a connection or a lock. The copy drops methods, fails, or copies a resource that must not have two owners.27
Do not implement ICloneable in a public .NET API. Microsoft recommends against it, because the interface does not say whether Clone is deep or shallow.13
Variants and related patterns
Abstract Factory. Design Patterns calls Prototype and Abstract Factory competitors in some ways, and says that they can work together: an abstract factory can store a set of prototypes and return copies of them.1 See Abstract Factory pattern.
Factory Method. A factory method needs a subclass of the creator for each product. A prototype needs no subclass, but it needs a copy operation on each product.1 See Factory Method pattern.
Composite and Decorator. Design Patterns says that designs that use Composite and Decorator often benefit from Prototype.1 A composite can be a prototype, so a copy of it copies a whole tree. This needs a deep copy. See Composite pattern and Decorator pattern.
Memento. A memento is also a copy of the state of an object, but its purpose is different. A prototype copy is a new object that lives on. A memento is a saved state that its originator restores later. See Memento pattern.
Flyweight. Flyweight is the opposite choice: it shares one object where Prototype makes many copies. A prototype whose fields are all immutable can be shared as a flyweight. See Flyweight pattern.
Copy with changes. Many languages make a copy with some fields changed in one expression: a C# with expression on a record, dataclasses.replace in Python, the spread syntax {...goblin, health: 50} in JavaScript, and the struct update syntax Monster { health: 50, ..goblin.clone() } in Rust. The C# with expression is shallow: a member of a reference type is shared between the copy and the original.14 These forms cover the common use of a prototype for value objects.
Known uses
- JavaScript: every object has a prototype, and
Object.createmakes an object with a given prototype.89 - Java: arrays implement
Cloneable, andcloneon an array of typeT[]returns aT[].3 - Self: objects are made by copying prototypes, and the language has no classes.10
References
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 3, Prototype (Intent, Motivation, Applicability, Participants, Consequences, Implementation, Related Patterns)
- The Python Standard Library, copy, Python 3.14, copy.copy, copy.deepcopy, the difference between shallow and deep copying, __copy__ and __deepcopy__
- Java SE 25 API, java.lang.Object, method clone, Implementation Requirements
- Java SE 25 API, java.lang.Cloneable, interface description
- Joshua Bloch, Effective Java, third edition, Addison-Wesley, 2018, Chapter 3, Item 13, Override clone judiciously
- HTML Living Standard, WHATWG, 2.7.11 Structured cloning API
- MDN Web Docs, The structured clone algorithm, Things that don't work with structured clone
- ECMA-262, ECMAScript 2025 Language Specification, 20.1.2.2 Object.create
- ECMA-262, ECMAScript 2025 Language Specification, 10.1.8.1 OrdinaryGet
- David Ungar and Randall B. Smith, SELF, The Power of Simplicity, Lisp and Symbolic Computation 4(3), 1991 (a revision of the OOPSLA 1987 paper, doi:10.1145/38765.38828), Abstract; section 2, Prototypes, Blending Classes and Instances (creation by copying)
- Henry Lieberman, Using prototypical objects to implement shared behavior in object-oriented systems, OOPSLA 1986, title and abstract
- .NET API reference, Object.MemberwiseClone, Remarks
- .NET API reference, ICloneable, Notes to Implementers
- C# language reference, Records, Nondestructive mutation
- Go standard library, package slices, func Clone
- Rust standard library, std::clone::Clone, trait description
- The Rust Reference, Traits, Dyn compatibility, rule items.traits.dyn-compatible.sized
- C++ Core Guidelines, C.67, A polymorphic class should suppress public copy/move
- C++ Core Guidelines, C.130, For making deep copies of polymorphic classes prefer a virtual clone function
- The Python Standard Library, dataclasses, Python 3.14, dataclasses.replace
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag KQHJFJ Edit this page History Report an error Markdown