Prototype
Category
Creational pattern
Problem
Create new objects by copying an existing instance (cloning), rather than creating them from scratch. Useful when object creation is expensive, or when you need to avoid subclassing just for object creation.
Solution
- Declare a
clone()orcopy()method on the prototype interface - Concrete prototype classes implement the clone method, returning a copy of themselves
- Client code requests a clone from the prototype, receives a new object with the same state
Structure
- Prototype: Interface declaring the
clone()method - ConcretePrototype: Implements the clone method; creates a copy of itself
- Client: Requests a clone from a prototype object
Key Benefits
- Avoids subclassing — No need to create a new class for each object variation
- Dynamic runtime configuration — Objects can be cloned at runtime based on current state
- Simplified object creation — No need to know the construction details of the object being cloned
- Performance — Cloning can be faster than constructing from scratch for complex objects
Trade-offs
- Deep vs. shallow copy — Must decide whether to copy nested objects deeply or just reference them
- Complex objects — Cloning objects with complex internal structures can be error-prone
- Circular references — Objects with circular references need special handling
When to Use
- When the cost of creating a new object is expensive compared to cloning
- You need to avoid the construction hierarchy of the class hierarchy
- You want to reduce the number of subclasses needed
- Instances of a class can have one of only a few different combinations of state