Prototype
Intermediate · 12 min read · Low-Level Design, Creational Patterns
Creating objects by cloning, deep vs shallow copies and prototype registries.
The idea in plain words
Sometimes the easiest way to make a new object is to copy one you already have, then change a little. Prototype gives objects a copy() method, so you can duplicate them even when you only know their interface, not their exact class.
The problem
You want an exact copy of an object. The naive approach — create a new instance of the same class and copy every field — has three issues:
The solution
Let the object copy itself. Declare a copy operation in a common interface; each class implements it, with full access to its own private state.
Shallow vs deep copy — the crux of the pattern
Rule of thumb: share immutable parts, copy mutable parts. In Polygon, the list is mutable (so it is copied) but each Point is an immutable record (so the points themselves are shared). If Point were mutable, the copy constructor would have to copy each point too — that is the deep copy.
Java's Cloneable — and why to avoid it
Java offers Object.clone() with the Cloneable marker interface. Effective Java (Item 13) explains why it's a poor mechanism:
Prototype registry
Keep a set of preconfigured prototypes and clone them on demand — useful when objects are built from expensive configuration.
When to use
Pros and cons
Related patterns
Interview questions
- What's the difference between a shallow and a deep copy, and how do you choose?
- Why does Effective Java advise against Cloneable?
- Give a practical use of Prototype in backend code.
Further reading
Key takeaways
- Prototype creates objects by copying an existing instance through a copy method on a shared interface.
- The real design decision is shallow vs deep copy: share immutable parts, copy mutable ones.
- Prefer copy constructors/factories over Cloneable in Java.
- A prototype registry gives cheap creation of preconfigured objects.