Prototype
You'll learn to
- -Clone existing objects instead of rebuilding them from scratch, and implement deep versus shallow copy correctly
- -Show with identity checks why a shallow copy shares nested mutable state
- -Use a prototype registry to spawn many similar objects
- -Identify the narrow set of interview problems where Prototype is the right call
Prototype creates new objects by copying an existing instance (the "prototype") rather than constructing one from scratch. It is the least frequently needed of the creational patterns in interviews, but it comes up cleanly whenever an object is expensive to construct and a similar, pre-configured instance already exists to clone from.
An Analogy: Save As
When you need a new spreadsheet that looks nearly like an existing, carefully formatted one, you do not rebuild it cell by cell. You open it and choose Save As, then change the few things that differ. The existing sheet is the prototype, and Save As is cloning. There is one trap: if the copy still points at the same chart or the same linked sheet as the original, editing it quietly edits the original. That trap is the whole subject of the next section.
Shallow vs. Deep Copy - the Part That Actually Trips People Up
A shallow copy duplicates an object's top-level fields, but if any of those fields are themselves references to mutable objects (a list, another object), both the original and the copy end up pointing at the same nested object - mutating it through the copy silently mutates the original too. A deep copy recursively clones every referenced object, so the copy is fully independent.
import copy
class GameCharacter:
def __init__(self, name: str, inventory: list[str]):
self.name = name
self.inventory = inventory # a mutable list
original = GameCharacter("Knight", ["sword", "shield"])
shallow = copy.copy(original)
shallow.inventory.append("potion")
print(original.inventory) # ['sword', 'shield', 'potion'] - the original changed too!
deep = copy.deepcopy(original)
deep.inventory.append("scroll")
print(original.inventory) # unaffected - deep copy owns its own independent listThe identity check makes it concrete. After shallow = copy.copy(original), the expression shallow is original is False, because they are two different objects, yet shallow.inventory is original.inventory is True: both point at the same list. After copy.deepcopy, the second check is False as well. Fields that are immutable, such as strings, numbers and tuples of them, are safe to share, since nobody can change them in place. The danger is mutable fields: lists, dictionaries and other objects.
A Prototype Registry
A common way to use Prototype is a registry of pre-built examples. To spawn an enemy you clone the matching prototype and tweak the clone. The expensive setup, loading models or computing stats, happens once:
class Registry:
def __init__(self):
self._prototypes = {}
def register(self, name, prototype):
self._prototypes[name] = prototype
def spawn(self, name):
return copy.deepcopy(self._prototypes[name])
registry = Registry()
registry.register("goblin", GameCharacter("Goblin", ["club"]))
enemy = registry.spawn("goblin") # independent copy, ready to modifyWhen Prototype Actually Earns Its Place
The pattern earns its place when object construction is genuinely expensive (a heavy computation, a database round-trip, an external API call to fully populate the object) and you have a pre-built instance close to what you need. Spawning 500 similar enemies in a game engine from one fully-configured prototype, or duplicating a complex, deeply-nested configuration object with one field tweaked, are the realistic interview-relevant use cases - most everyday object creation should just use a constructor or Builder instead.
Cloning is not free either. A deep copy of a large structure costs time and memory, so the saving only exists if building from scratch is more expensive than copying. Measure before you claim it.
If you reach for Prototype in an interview for a cheap-to-construct object, that is usually a sign you are pattern-matching rather than solving the actual problem - name the expense (construction cost, external calls) that justifies cloning over constructing.
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.
Discussion0
Join the Discussion
Sign in to leave comments, reply to others, or like insights.
No comments yet. Be the first to start the thread!