Prototype Pattern
Make new objects by copying a configured one instead of building from scratch, and know exactly what a copy shares with its original.
Overview
Prototype is a creational pattern from the Gang of Four book (Gamma, Helm, Johnson and Vlissides, *Design Patterns*, 1994). Instead of naming a class and calling its constructor, the client keeps a configured object, the prototype, and asks it for a copy. New variants come from copying and adjusting, not from new subclasses.
The pattern is small; what interviewers test is the copy itself. A shallow copy makes a new outer object whose fields point at the same inner objects as the original. A deep copy makes new inner objects too. Pick the wrong one and two objects that should be independent change together. Most Prototype questions are really shallow-versus-deep questions.
Python and Java both ship the machinery: Python's copy module and copy / deepcopy hooks, and Java's Object.clone() with the Cloneable marker. Knowing what each does by default is the difference between a good answer and a wrong one.
The shape of the pattern
The pattern needs only an interface with a clone() method, the classes that implement it, and usually a registry that holds named templates.
Interview questions
- Show a bug caused by a shallow copy and how you fix it.
- How do you implement Prototype correctly in Python and in Java?
- When is Prototype the right pattern, compared with a factory or a builder?
- Copy constructor or clone(): which do you recommend?
- What goes wrong when Prototype is used carelessly?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio