Patterns: behavior · 3 MIN READ
Strategy: choose an algorithm explicitly
Pass interchangeable behavior through a function or small interface.
Pass interchangeable behavior through a function or small interface. Strategy isolates an algorithm that changes independently of its caller. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.
Behavioral pattern · A MAP OF THE IDEA
- Caller selects an algorithm
- Context owns stable workflow
- Strategy performs the varying step
Useful when
- Algorithms vary independently of the workflow
- Tests need deterministic alternative behavior
Watch out
- Mutation and errors belong in the contract
- A small fixed switch may be simpler
Implementation & operation cost: Low
Fit depends on the task
Editorial suitability, not benchmarks or a universal ranking. Styles describe different axes and can be combined.
The design decision
Strategy isolates an algorithm that changes independently of its caller. Go function values cover many one-method strategies without extra types. Select the strategy at the composition boundary and keep domain inputs clear instead of switching on a global mode in every call.
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"
"sort"
)
type Rank func([]int)
func Present(values []int, rank Rank) []int {
copy := append([]int(nil), values...)
rank(copy)
return copy
}
func main() {
values := []int{3, 1, 2}
fmt.Println(Present(values, sort.Ints))
fmt.Println(values)
}
// Output:
// [1 2 3]
// [3 1 2]
Present controls copying and delegates ordering to the selected function. The original slice remains unchanged, so strategy selection does not surprise its caller with mutation. A reverse ordering function could be supplied without editing Present.
Tradeoffs and the simpler alternative
Use direct branching for a small fixed choice that does not need independent extension. A strategy is not a justification for a new interface around every expression. Document whether it may mutate input, return errors or run concurrently.
TAKE THIS WITH YOU
Makes a varying algorithm an explicit dependency. Use direct branching for a small fixed choice that does not need independent extension. A strategy is not a justification for a new interface around every expression. Document whether it may mutate input, return errors or run concurrently.
Check your understanding
Which statement best describes Strategy: choose an algorithm explicitly?
Go to the source
Progress stays in this browser. No account needed.