Behavioral

Strategy

Defines a family of algorithms and makes them interchangeable.

Sorting algorithmsPayment methodsCompression

Understanding Strategy

The Strategy pattern defines a family of interchangeable algorithms, encapsulates each one behind a common interface, and lets clients switch between them at runtime. Instead of hardcoding a single algorithm with conditional logic, you extract each variant into its own struct implementing a shared interface. In Go, the context struct holds an interface field for the current strategy — calling SetStrategy()swaps the behavior without changing the context code. This is one of Go\'s most natural patterns since interfaces and composition are first-class concepts.

Key Concepts

  • Strategy interface — defines the contract (e.g., Sort, Pay, Compress) that all algorithm variants must follow
  • Concrete strategies — individual structs implementing the interface with specific algorithm logic
  • Context — holds a strategy reference and delegates the algorithm call — doesn\'t know which strategy is active
  • Runtime swapping — strategies can be changed at runtime via a setter, enabling dynamic behavior selection

When to Use

✅ Use when
  • • You have multiple algorithms for the same task and need to switch between them
  • • You want to eliminate conditional statements selecting between behaviors
  • • Algorithm implementations should be isolated for testing and reuse
  • • The behavior needs to change at runtime based on user input or configuration
⚠️ Avoid when
  • • You only have 2 strategies that never change — a simple if/else is clearer
  • • The algorithm is tightly coupled to the context\'s internal state
  • • Clients don\'t need to know about the strategies — a factory may be better

Structure

Context (holds strategy)
↓ uses
<<Strategy Interface>>
↓ implements
StrategyA
StrategyB
StrategyC

How It Works

Context
Sorter
strategy: null
Strategies
🔵 Strategy A
🟢 Strategy B
🟣 Strategy C
Context needs algorithm
1

Context

Context needs to perform an operation.

1 / 4

Basic Implementation

Sorting with interchangeable algorithms:

main.go
Loading editor...

Real-World Example: Payment Processing

Shopping cart with multiple payment methods:

main.go
Loading editor...