Prototype
Intent
Copies existing objects without making code depend on their classes.
Problem
Copying an object from the outside requires knowing its concrete class and private fields.
Solution
Objects implement a clone method themselves.
Real-world analogy
Think of it like this
Cell division: a cell copies itself. No outside factory needs to know how the cell is built.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1Prototype — Prototype declares the cloning method.
- 2ConcretePrototype — Concrete Prototype implements clone by copying its own fields, including private ones.
- 3SubclassPrototype — Subclasses override clone to copy their extra fields too.
- 4Client — Client copies any object through the Prototype interface without knowing its class.
Code example
A C# code sample for Prototype is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.
Applicability
Use Prototype when code shouldn't depend on concrete classes of objects to copy.
Use Prototype when reducing subclasses that differ only in initialisation.
Pros and cons
Pros
- Clone without coupling to classes
- Pre-built prototypes replace repeated setup
Cons
- Cloning objects with circular references is tricky
Relations with other patterns
Check yourself
Check yourself
Spawning thousands of enemies whose setup is expensive; you want to copy one configured template enemy.
Saved in this browser only. Part of Creational patterns (0/5).