Strategy (Behavioral)
Intent / problem it solves
Define a family of algorithms, encapsulate each one, and make them interchangeable at runtime. Lets the algorithm vary independently from clients.
When to use / when NOT
Use for pricing rules, shipping calculators, compression codecs, or anything swappable by configuration.
Avoid when only one implementation exists (YAGNI) or when functions suffice without interfaces.
Structure
Context holds a strategy interface; concrete strategies implement the single method family.
Loading diagram…
Go example
package main
import "fmt"
type PricingStrategy interface {
Quote(amount float64) float64
}
type StandardPricing struct{}
func (StandardPricing) Quote(amount float64) float64 { return amount }
type MemberPricing struct{ Discount float64 }
func (pricing MemberPricing) Quote(amount float64) float64 {
return amount * (1 - pricing.Discount)
}
type Cart struct {
strategy PricingStrategy
}
func (cart Cart) Total(amount float64) float64 {
return cart.strategy.Quote(amount)
}
func main() {
memberCart := Cart{strategy: MemberPricing{Discount: 0.1}}
fmt.Println(memberCart.Total(100))
}JavaScript example
class CheckoutContext {
constructor(strategy) {
this.strategy = strategy;
}
setStrategy(strategy) {
this.strategy = strategy;
}
checkout(amount) {
return this.strategy.calculate(amount);
}
}
const standard = {
calculate: (amount) => amount,
};
const coupon = {
calculate: (amount) => Math.max(0, amount - 5),
};
const register = new CheckoutContext(standard);
console.log(register.checkout(40));
register.setStrategy(coupon);
console.log(register.checkout(40));Interview phrase
“Strategy injects behavior instead of branching—great for A/B tests, tenant-specific rules, or plugging new algorithms without editing the caller.”
Related LLD case studies
Map to LLD for pricing, sorting policies, or validation rule packs in LLD case studies.
Last updated on
Spotted something unclear or wrong on this page?