All PatternsCreational
Prototype
Creates new objects by copying an existing object (prototype).
Object cloningCache systemsDefault configurations
Understanding Prototype
The Prototype pattern creates new objects by cloning an existing instance rather than constructing from scratch. This is particularly useful when object creation is expensive (involves DB queries, network calls, or complex computation) or when you need many similar objects with slight variations. In Go, this is implemented via a Clone() method that performs a deep copy — critically important for reference types like maps and slices to ensure the clone is truly independent from the original.
Key Concepts
- •Clone interface — objects implement a
Clone()method that returns an independent copy of themselves - •Deep vs. shallow copy — shallow copies share pointers, maps, and slices with the original; deep copies duplicate everything to ensure full independence
- •Prototype registry — a collection of pre-configured prototypes keyed by name, allowing you to retrieve and clone templates on demand
- •Post-clone customization — after cloning, the copy can be modified independently without affecting the original prototype
When to Use
✅ Use when
- • Object creation is expensive and you need many similar instances
- • You want to avoid complex initialization logic for each new object
- • You need to create variations from pre-configured templates
- • The object's class hierarchy is complex and you want to avoid duplicating factory code
⚠️ Avoid when
- • Objects are cheap to create — direct construction is simpler
- • The object has circular references that make deep copying complex
- • A simple struct literal or builder pattern would suffice
Structure
<<Cloneable>> Clone() Cloneable
↓ implements
Prototype (original)
↓ Clone()
Clone 1 (modified)
Clone 2 (modified)
Clone N
How It Works
Original
Title: "Template"
Author: "System"
Content: "..."
Clone()
Clone
Title: "Template"
Author: "System"
Content: "..."
1
Original Object
Start with an existing fully configured object.
1 / 4
Basic Implementation
Cloning document templates:
main.go
Loading editor...
Real-World Example: Configuration Cloning
Creating environment-specific configs from a base template with deep copying:
main.go
Loading editor...