design patterns ·
Prototype
Creates new objects by cloning an existing instance, avoiding expensive re-initialization.
Theory
Explanation
Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.
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).
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