Prototype
medium 50 minThe Prototype pattern makes new objects by copying an existing one.
Video lesson · Chapter 1 of 6
Make a prediction
Prototype
1:06Reel
Theory
Read or listen first. About 2 min.
What it is
Prototype is a creational design pattern. You keep an object that is already right, the prototype, and make new ones by asking it to copy itself.
The caller sees one method, usually called clone or copy. Which class is copied, how many inner objects it has, and how long it took to build are the prototype's business.
A prototype registry keeps several prepared prototypes under names and gives out clones of them.
Why it exists
Some objects are expensive to build: they read files, ask a database, or calculate for seconds. Copying what is in memory costs far less, as long as the copy is cheaper than the build.
Some objects are made by people. When a user presses Duplicate, no list of constructor arguments exists, only the finished object.
Copying from outside needs public fields and a type check per class, and it slices subclasses. Copying from inside needs neither.
Variants that differ in values become data instead of subclasses. A designer can add one while the program runs.
A short history
1963
Ivan Sutherland submits the Sketchpad thesis at MIT. In it users draw a master and place instances of it, an early ancestor of the idea.
1987
David Ungar and Randall Smith present Self: The Power of Simplicity at OOPSLA. In Self there are no classes; new objects are made by copying prototypes.
1994
The book Design Patterns lists Prototype among its creational patterns.
2015
Object.create, which makes a new object with a given prototype, has worked in all major browsers since July of that year according to MDN.
Words to know
- Prototype
- An object that is kept in order to be copied.
- Clone
- The copy, and the method that makes it.
- Shallow copy
- A new outer object. Inner objects are shared.
- Deep copy
- New inner objects as well, all the way down.
- Copy constructor
- A constructor that takes an object of the same class and copies it.
- Covariant return type
- An override that returns a narrower type than the method it overrides.
- Slicing
- Copying only the base part of an object of a subclass.
- Registry
- A map from name to prototype that gives out clones.
- Memo
- The map from original to copy that a deep copy keeps while it runs.
- Copy on write
- Share now, copy at the first change.
- Torn copy
- A copy with fields from two different moments.
- Delegation
- Asking another object at each read, as JavaScript prototypes do. Not copying.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Build one. Expensive or configured by a person
Understand it
Start here
A plant that copies itself
You can make a strawberry plant in two ways. Sow a seed, wait a year, and see what you get. Or let a good plant grow a runner: a long stem with a small plant at its end, the same sort as its mother. The Prototype pattern is the second way, for objects.
The whole pattern is in two questions: who makes the copy (the object itself), and what does the copy share (you decide, field by field).
Four parts
Prototype
The interface with one method,
clone. Examples:Shape,Document.Concrete prototype
A class that knows how to copy its own fields, including the inner objects. Examples:
Circle,Rectangle,Invoice.Client
Asks for a copy and changes it. Knows the interface only. Examples: a shape editor, a document manager.
Registry (optional)
A catalog of prepared prototypes by name. Gives out clones. Examples:
ShapeRegistry, a template store.
Why
Why not just call the constructor?
Often you should. The constructor is the normal way. Copying becomes the better way in four situations.
| Situation | With the constructor | With a prototype |
|---|---|---|
| Building is slow: files, network, parsing, long calculation | Every object pays again | Pay once, then copy what is in memory |
| The object was configured by a person, step by step | The steps are lost, only the result exists | Copy the result: duplicate this slide |
| The class is only known at run time | A chain of type checks | selected.clone(), whatever it is |
| Many variants differ only in values | A subclass for each: BigRedCircle, SmallBlueCircle | One class, many prepared prototypes |
class Circle: def __init__(self, radius, color): self.radius, self.color = radius, colorclass GlowCircle(Circle): # added a year later def __init__(self, radius, color, glow): super().__init__(radius, color) self.glow = glowdef duplicate(shape): # in the editor, written before GlowCircle if isinstance(shape, Circle): return Circle(shape.radius, shape.color) raise TypeError("unknown shape")lamp = GlowCircle(8, "yellow", glow=40)copy = duplicate(lamp)print(type(lamp).__name__, "became", type(copy).__name__, "and has a glow:", hasattr(copy, "glow"))No error, no warning. The user pressed Duplicate and the glow was gone. The editor is the wrong place for this knowledge. The only class that always knows all its fields is the class itself.
The design that hurts: copied from outside
1/2One editor, three classes
duplicate asks for the class, reads the fields and calls the right constructor. The fields can no longer be private.
depends onextends (is a)
The Prototype pattern in general
1/4The interface
One method. The result has the same class as the object that was asked, and callers do not need to know which.
usesowns (dies together)implements
One clone, deep
The crux
Shallow or deep?
A variable that holds an object holds a reference, an arrow to it. A shallow copy makes a new outer object and copies the arrows. A deep copy follows the arrows and makes new inner objects too.
What the arrows look like
import copyclass Point: def __init__(self, x, y): self.x, self.y = x, yclass Circle: def __init__(self, radius, center): self.radius, self.center = radius, centeroriginal = Circle(20, Point(0, 0))shallow = copy.copy(original)deep = copy.deepcopy(original)shallow.radius = 99 # replaces a value in the copy onlyshallow.center.x = 100 # reaches through the shared arrowdeep.center.x = 555print("original:", original.radius, original.center.x) # 20 100print("same center:", shallow.center is original.center, deep.center is original.center)Look at the two lines again. shallow.radius = 99 is harmless and shallow.center.x = 100 is not. Assigning to a field of the copy changes the copy. Changing an object behind a field changes what both share.
The same two ideas in six languages
| Language | Shallow | Deep |
|---|---|---|
| Python | copy.copy(x), x[:], dict(x) | copy.deepcopy(x) |
| JavaScript | { ...x }, Object.assign({}, x) | structuredClone(x) for data; loses your class, rejects functions |
| Java | super.clone() | Copy constructor or copy() written by hand |
| C++ | Default copy of a class with raw or shared pointers | Own copy constructor. Members that are values copy deep by default |
| C# | MemberwiseClone() | By hand. ICloneable does not say which one it means |
| Go | b := a for a struct | By hand, or a Clone method such as http.Request.Clone |
What to do with one field
A slide has a title, a list of boxes, a theme and an id. The user presses Duplicate. What does clone do?
BreaksCopy all fields as they are
- How
copy.copy(slide).- Limit
- Both slides share one list of boxes, and both have the same id. Moving a box moves it on both, deleting one slide deletes the other in the database.
- Choose when
- Only if all fields are values that never change.
WorksCopy everything deep
- How
copy.deepcopy(slide).- Limit
- The theme is copied too. Change the company colour once, and the copy keeps the old one. The id is still doubled.
- Choose when
- A plain tree of data without identity.
StrongOne decision per field
- How
- Title: share, strings do not change. Boxes: copy each. Theme: share on purpose. Id: make a new one.
- Limit
- Somebody must decide again for each new field. A test reminds them.
- Choose when
- Every object with identity or shared parts, which is most of them.
Scale
A registry of prototypes
With three or more prepared objects you want names for them. A prototype registry is a map from name to prototype. Its two rules are the whole design.
- 1
Copy on the way in
registerstores a clone. Otherwise the person who registered it still holds the prototype and can change it. - 2
Copy on the way out
getreturns a clone. Otherwise the first client who paints it green paints it for everyone after them. - 3
Unknown name: say so
Raise an error with the name. A silent
Noneturns up later, far away.
Asking a registry
Choosing
When to use it and when not
Use it when
- Building is expensive and the result can be copied
- Users duplicate what they made: shapes, slides, invoices
- You must copy without knowing the class
- A class would need many subclasses that differ in values only
- You need a whole structure again, with its inner links
Leave it when
newwith three arguments does the job- The object never changes: share it, do not copy it
- It owns something unique: a socket, a thread, a file, a lock
- Copying costs as much as building
- Nobody can say what a correct copy is
A cycle in the object graph is not on the list of reasons against it. A naive deep copy runs forever on a cycle, and a copy that remembers what it has already copied does not. Python's deepcopy and structuredClone both remember. The page on graphs shows how.
How to get a new object
Real cases
| Object | Copied | Shared | New |
|---|---|---|---|
| Enemy in a game | Health, position, inventory | Mesh, texture, animation | Entity id |
| Invoice from a template | Lines, payment terms | Logo, letterhead | Number, date, history |
| HTTP request before a retry | Headers, query | Connection pool | Attempt count, trace span |
| Slide | Boxes, notes | Theme | Slide id |
| Training job | Settings | Data set | Run id, log file |
Summary
The whole topic in one minute.
Prototype lets an object copy itself. The caller needs no class name, private fields stay private, and expensive work is done once. A registry names prepared prototypes and copies on the way in and on the way out.
Deep or shallow is decided for each field: share what never changes, copy what does, renew what identifies, reset what belongs to the past. Cycles and shared parts need a map from original to twin that is filled before links are followed.
In production: prototypes are frozen and replaced whole, every class copies its own fields and a test checks class, values and independence, and large copies are postponed to the first write. If everything is immutable, replace some fields and forget the pattern.
- The object copies itself. Only its own class knows all its fields.
- Shallow copies the arrows, deep copies what they point to. Decide for each field: share, copy, renew, reset.
- Assigning a field changes the copy. Changing an object behind a field changes both.
- A registry copies on the way in and on the way out.
- Cycles need a memory of what was copied already.
- You trade time for memory: one object is kept only to be copied.
- If it never changes, do not copy it. Share it.
Sources
- Python: copy, shallow and deep copy operations
- MDN: structuredClone
- MDN: Node.cloneNode
- Java SE 21: Object.clone
- Josh Bloch on Design (interview, copy constructor and cloning)
- C++ Core Guidelines C.130: virtual clone
- .NET: ICloneable
- Linux manual: fork(2)
- Self: The Power of Simplicity (1987)
- Ivan Sutherland: Sketchpad
- Design Patterns (publisher's page)