AlgoViz

Prototype

medium 50 min

The Prototype pattern makes new objects by copying an existing one.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:34

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

  1. 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.

  2. 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.

  3. 1994

    The book Design Patterns lists Prototype among its creational patterns.

  4. 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.

Step 1 of 3

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.

Asha and the strawberry mothers
1 YEAR

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.

SituationWith the constructorWith a prototype
Building is slow: files, network, parsing, long calculationEvery object pays againPay once, then copy what is in memory
The object was configured by a person, step by stepThe steps are lost, only the result existsCopy the result: duplicate this slide
The class is only known at run timeA chain of type checksselected.clone(), whatever it is
Many variants differ only in valuesA subclass for each: BigRedCircle, SmallBlueCircleOne class, many prepared prototypes
The last row is why a level designer can add a new enemy without a programmer: a new prototype is data, not a class.
Python
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"))
Run it. Duplicating from outside has to know every class, and it forgets what it does not know.
Edit and run it in your browser

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

Editor+ duplicate(shape)- if Circle ...- if Square ...- if Group ...Circle- radius- color- textureSquare- side- colorGroup- children

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)

Every new class and every new field means an edit in the editor, and nothing reminds you.

The Prototype pattern in general

«interface»Prototype+ clone(): Prototype

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

Without a registry the client simply holds a prototype, for example the selected shape.

One clone, deep

Numbers and strings are copied as they are. The Point is changeable, so it gets a twin.

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

Both copies look equal on the first day. The difference shows on the first change.
Python
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)
The same change, two results.
Edit and run it in your browser

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

LanguageShallowDeep
Pythoncopy.copy(x), x[:], dict(x)copy.deepcopy(x)
JavaScript{ ...x }, Object.assign({}, x)structuredClone(x) for data; loses your class, rejects functions
Javasuper.clone()Copy constructor or copy() written by hand
C++Default copy of a class with raw or shared pointersOwn copy constructor. Members that are values copy deep by default
C#MemberwiseClone()By hand. ICloneable does not say which one it means
Gob := a for a structBy hand, or a Clone method such as http.Request.Clone
Old advice is to write JSON and parse it again. It loses dates, undefined, class instances and cycles. Use it for plain data only.

What to do with one field

Deep and shallow are not the two choices. Each field gets its own answer: share, copy, renew or reset.

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. 1

    Copy on the way in

    register stores a clone. Otherwise the person who registered it still holds the prototype and can change it.

  2. 2

    Copy on the way out

    get returns a clone. Otherwise the first client who paints it green paints it for everyone after them.

  3. 3

    Unknown name: say so

    Raise an error with the name. A silent None turns up later, far away.

Asking a registry

The arrow from the client never reaches the prototype.

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

  • new with 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

Flyweight, Factory method and Builder have their own pages.

Real cases

ObjectCopiedSharedNew
Enemy in a gameHealth, position, inventoryMesh, texture, animationEntity id
Invoice from a templateLines, payment termsLogo, letterheadNumber, date, history
HTTP request before a retryHeaders, queryConnection poolAttempt count, trace span
SlideBoxes, notesThemeSlide id
Training jobSettingsData setRun id, log file
The enemy of the first row: load the orc warlord with mesh, textures and animations once, then clone it fifty times at fifty positions.

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