design patterns · creational
Prototype
Creates new objects by cloning an existing instance, avoiding expensive re-initialization.
Pattern
Overview
Intent
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
Real-World Analogy
Photocopying a document - faster than retyping it from scratch when you need multiple similar copies.
When creating an object is expensive (DB lookup, heavy config) but you need many similar instances, clone a fully initialized prototype and tweak the copy.
Prototype objects implement a clone() method. Java provides Cloneable + super.clone() for shallow copies; deep copies require manual collection copying. The client calls clone() instead of new.
When to use
When object construction is expensive (DB-loaded objects, heavy config), when you need many instances that differ only slightly from a base template.
When not to
When construction is cheap. When objects contain uncloneable resources (open file handles, threads).
Participants
Key Insights
- Shallow copy copies field references - mutations to mutable fields affect both original and copy
- Deep copy clones all contained objects recursively - safe but must be done explicitly
- Java Cloneable is a marker interface; clone() is defined on Object, not Cloneable
- Serialization-based cloning (serialize then deserialize) is a common deep-copy workaround