Patterns: creation · 3 MIN READ
Prototype: copy a useful starting value
Choose shallow or deep copying according to ownership.
Choose shallow or deep copying according to ownership. Prototype creates an object from an existing configured object. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.
Creational pattern · A MAP OF THE IDEA
- Select an existing configured value
- Copy owned mutable collections
- Customize an independent result
Useful when
- Templates contain useful repeatable configuration
- Callers need isolated editable drafts
Watch out
- Shallow copies can retain shared mutable elements
- Resource handles should not be cloned
Implementation & operation cost: Low to medium
Fit depends on the task
Editorial suitability, not benchmarks or a universal ranking. Styles describe different axes and can be combined.
The design decision
Prototype creates an object from an existing configured object. A Go struct assignment copies fields, but maps, slices and pointers may still refer to the original storage. Define what cloning promises before using a prototype as an independent editable draft.
A complete Go example
Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.
package main
import (
"fmt"
"maps"
"slices"
)
type Template struct {
Tags []string
Limits map[string]int
}
func (t Template) Clone() Template {
return Template{Tags: slices.Clone(t.Tags), Limits: maps.Clone(t.Limits)}
}
func main() {
original := Template{Tags: []string{"go"}, Limits: map[string]int{"cpu": 2}}
copy := original.Clone()
copy.Tags[0] = "rust"
copy.Limits["cpu"] = 4
fmt.Println(original.Tags[0], original.Limits["cpu"])
}
// Output:
// go 2
The clone owns a different slice backing array and a different map, so mutation does not change original. The elements here are immutable strings and integers; pointer or nested slice elements would require another deliberate copy decision.
Tradeoffs and the simpler alternative
Copying a network connection or mutex is not a valid general cloning strategy. Keep resource handles out of reusable prototypes. If a value is already small and immutable, an ordinary assignment is simpler than a named Clone method.
TAKE THIS WITH YOU
Copies the state needed for an independent starting value. Copying a network connection or mutex is not a valid general cloning strategy. Keep resource handles out of reusable prototypes. If a value is already small and immutable, an ordinary assignment is simpler than a named Clone method.
Check your understanding
Which statement best describes Prototype: copy a useful starting value?
Go to the source
Progress stays in this browser. No account needed.