☰ All patterns
Strategy
Swap algorithms at runtime behind one interface.
01
Explain it like I'm new
Real-life analogy
Getting to the airport
Car, train or bike: the goal is the same and you pick the strategy based on time and budget. The trip planner doesn't care how each works.
😩 The problem
Shipping cost depends on the method chosen. A growing switch statement in Cart mixes cart logic with every pricing rule.
💡 The pattern
Put each algorithm behind a common interface. Cart holds a strategy and calls it, and you can swap strategies at runtime.
02
Play with it
An interactive model of the pattern. Click around, nothing can break.
💡 The Cart code never changes. You only swap which strategy it holds.
03
Walk through the code
Click a step to highlight its lines. This is a complete program you can copy and run.
Press ▶ Run to execute this program.This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.
04
When should I use it?
✅ Reach for it when…
- •Multiple interchangeable algorithms: pricing, compression, sorting, auth methods.
🚫 Skip it when…
- •There's only one algorithm and no plan for more.
🐹 Go tip
For one-method strategies, a function type is often simpler: type CostFunc func(kg float64) float64.
🌍 You've already seen it in
sort.Slice(data, less) takes the comparison strategy as a function. hash.Hash implementations are interchangeable.
05
Quick check
One question. No pressure.
sort.Slice(people, func(i, j int) bool {...}): what's the strategy here?