Prototype
medium 50 minThe Prototype pattern makes new objects by copying an existing one.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Who holds which object after a copy, and whose value changes.
Operations
Clone and change
Two clones of one prototype. One of them is painted and moved.
Step 1 of 7
Registered
The registry keeps its own copy of the big red circle.
Step 1: Registered
class ShapeRegistry: def register(self, key, prototype): self._prototypes[key] = prototype.clone() def get(self, key): return self._prototypes[key].clone()registry.register("BigRed", Circle(20, Point(0, 0), "red"))s1 = registry.get("BigRed")s2 = registry.get("BigRed")s1.color = "green"s1.center.x = 100s2.draw()- Watch
- The third object
- Result
- Prototype untouched
Watch bigRed. Nothing in it ever changes.
In the real world
The same prototype doing real jobs. Pick one and step through it.
get returns the prototype itself. One client paints it.
Step 1 of 3
First client
It gets the prototype, not a copy.
Step 1: First client
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Sharing the inner list
criticalThe copy and the original have one list.
Wrongdef clone(self): return Slide(self.title, self.boxes)Rightdef clone(self): return Slide(self.title, [b.clone() for b in self.boxes])Giving out the prototype
criticalThe first client who changes it changes it for all.
Wrongdef get(self, key): return self._prototypes[key]Rightdef get(self, key): return self._prototypes[key].clone()Remembering the twin too late
criticalOn a cycle the second arrival does not find it, and the recursion never ends.
Wrongtwin.links = [n.clone(seen) for n in self.links]seen[id(self)] = twinRightseen[id(self)] = twintwin.links = [n.clone(seen) for n in self.links]A default dictionary as memo
majorPython makes it once. All calls share it, and old twins come back.
Wrongdef clone(self, seen={}):Rightdef clone(self, seen=None): seen = {} if seen is None else seenCopying the identity
majorTwo invoices with one number.
Wrongcopy.number = template.numberRightcopy.number = next_number()Naming the class in the parent
majorA subclass that inherits clone is copied as its parent.
Wrongtwin = Circle(self.radius)Righttwin = object.__new__(type(self))
Interview tips
Before you write clone
- Draw the object and its arrows
- Give each field a verb
- Filled diamond: copy. Open diamond: share
Good signs
- Clone sits next to the fields
- The test changes the copy
- Prototypes have no setters
Warning signs
- Type checks outside the class
- deepcopy on business objects
- An id in two objects
In the interview
- Say share, copy, renew, reset
- Mention the memo before they ask
- Offer immutability as the way out