Strategy
Definition
Strategy
- In plain English
- Strategy puts each version of an algorithm behind one interface so the caller can swap which one it uses.
- Think of it like
- It is like a sat-nav letting you choose fastest, shortest or no-motorways route.
Why it exists
Weekday, weekend and long-term rules repeat across billing. Every new plan adds another chain of conditions.
Choose a pricing rule once, then pass it to booking code. That code can use any rule with the same contract.
How it works
Function type
- In plain English
- A function type names a function signature, so any function with that shape can be passed around as a value.
- Think of it like
- Like a job title that anyone with the right skills can fill.
package main
import "fmt"
type Pricer interface{ Price(int) int }
type Weekday struct{}
func (Weekday) Price(days int) int { return days * 4000 }
type Weekend struct{}
func (Weekend) Price(days int) int { return days * 5000 }
type LongTerm struct{}
func (LongTerm) Price(days int) int { return days * 3000 }
type Booking struct{ pricing Pricer }
func (b Booking) Total(days int) int { return b.pricing.Price(days) }
func main() { fmt.Println((Booking{Weekend{}}).Total(2)) }
package main
import "fmt"
type PriceFunc func(int) int
func total(days int, price PriceFunc) int { return price(days) }
func main() {
rules := map[string]PriceFunc{
"weekday": func(days int) int { return days * 4000 },
"weekend": func(days int) int { return days * 5000 },
"long-term": func(days int) int { return days * 3000 },
}
rule, ok := rules["weekend"]
if !ok {
fmt.Println("unknown plan")
return
}
fmt.Println(total(2, rule))
}
Weekday, Weekend and LongTerm satisfy Pricer; Booking uses Pricer without choosing the implementation.
The caller chooses the strategy. Check configuration names before calling a function selected from a map.
Examples
Select a pricing plan
Your booking chooses weekday, weekend or long-term pricing. Totals use whole days and integer cents.
package main
import "fmt"
type PriceFunc func(int) int
func total(days int, price PriceFunc) int { return price(days) }
func main() {
rules := map[string]PriceFunc{
"weekday": func(days int) int { return days * 4000 },
"weekend": func(days int) int { return days * 5000 },
"long-term": func(days int) int { return days * 3000 },
}
rule, ok := rules["weekend"]
if !ok {
fmt.Println("unknown plan")
return
}
fmt.Println(total(2, rule))
}
These sample rates demonstrate interchangeable rules. A real booking must also reject negative days and apply its own pricing terms.
The insight
Booking code stays the same while pricing varies.
Choose a lobby rule
Each playlist chooses skill matching, lowest network delay, or the first waiting player. The lobby uses one function shape.
package strategies
import "fmt"
type Player struct {
Name string
Skill, Ping int
}
type Match func([]Player) (Player, bool)
func Skill(players []Player) (Player, bool) {
if len(players) == 0 {
return Player{}, false
}
best := players[0]
for _, p := range players[1:] {
if p.Skill > best.Skill {
best = p
}
}
return best, true
}
func LowPing(players []Player) (Player, bool) {
if len(players) == 0 {
return Player{}, false
}
best := players[0]
for _, p := range players[1:] {
if p.Ping < best.Ping {
best = p
}
}
return best, true
}
func Casual(players []Player) (Player, bool) {
if len(players) == 0 {
return Player{}, false
}
return players[0], true
}
func Demo() {
playlists := map[string]Match{"ranked": Skill, "quick": LowPing, "casual": Casual}
fmt.Println(playlists["quick"]([]Player{{"A", 8, 40}, {"B", 6, 20}}))
}
Ping measures network delay; lower is better. This small selection example picks the highest skill score rather than forming full teams.
The insight
A function type is a lightweight strategy.
Switch allocation rules
During shortages, staff select first-come, highest-need or equal-share allocation. Your application reads the selected rule name.
package strategies
import "fmt"
type Allocation func(int, []int) []int
func FirstCome(stock int, need []int) []int {
out := make([]int, len(need))
for i, n := range need {
if n > stock {
n = stock
}
out[i] = n
stock -= n
}
return out
}
func MostNeed(stock int, need []int) []int {
out := make([]int, len(need))
for stock > 0 {
best := -1
for i, n := range need {
if n > out[i] && (best < 0 || n-out[i] > need[best]-out[best]) {
best = i
}
}
if best < 0 {
break
}
out[best]++
stock--
}
return out
}
func FairShare(stock int, need []int) []int {
out := make([]int, len(need))
for stock > 0 {
changed := false
for i, n := range need {
if stock > 0 && out[i] < n {
out[i]++
stock--
changed = true
}
}
if !changed {
break
}
}
return out
}
func Demo() {
rules := map[string]Allocation{"first": FirstCome, "need": MostNeed, "fair": FairShare}
selected := "fair"
fmt.Println(rules[selected](4, []int{3, 3}))
}
Inputs here are nonnegative units and needs. A real configuration update must validate the selected name before swapping the active rule.
The insight
Strategies can be chosen while the program runs.
Trade-offs
Pros
- Swap algorithms independently.
- Test each rule alone.
- Keep callers free of condition chains.
Cons
- The caller must choose.
- Many tiny types can add noise.
Use when
- Several ways perform the same task.
- Rules change independently of callers.
Avoid when
- Only one rule exists.
- A stable two-branch decision already reads well.
Quick check
Takeaways
- Strategy = interchangeable algorithms behind one interface.
- The caller picks; the code using it doesn't change.
- In Go, a function type often suffices.