Behavioral

Strategy

Defines a family of algorithms and makes them interchangeable.

Sorting algorithmsPayment methodsCompression

Understanding Strategy

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

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...