Understanding the Strategy Pattern
Learn how to swap one behavior for another cleanly by encapsulating algorithms behind a common interface and choosing which one to use at runtime.
Why this pattern matters
Most applications rarely have just one way to accomplish a task. We begin with a simple password login. Then the product team asks for “Login with Google,” and later “Send OTP for mobile users.”
Before long, our authentication code is littered with conditional branches:
If password → do this
If Google → do that
If OTP → do something else
Each time we add a new method, we touch old logic and retest everything. The same problem arises in payments, pricing, shipping, and caching: every feature that depends on context introduces another conditional.
At this point, our code stops scaling. Instead of adding features, we’re adding complexity.
The Strategy Pattern addresses this by keeping each behavior separate, providing them with the same interface, and allowing your app to choose which one to use at runtime. We no longer touch working code just to add new behavior. Instead, we think in terms of strategies, not branches.
How the pattern works
We define a set of interchangeable strategies—each one a self-contained approach to accomplishing the same task. In the example above, each authentication method—password, Google, OTP—is a strategy. They all expose the same interface, say authenticate(credentials), so they can be swapped freely without breaking the rest of the flow.
But we still need something to use those strategies. That’s the context—the stable piece that defines the workflow. The context handles the common steps of authentication:
Receive credentials.
Select or inject the right strategy.
Delegate verification to that strategy.
Handle the result.
That workflow never changes. The part that varies—how verification happens—is the strategy’s responsibility. Think of the context as the login service: the orchestration stays the same, but the verification method can change. Today it’s password-based, tomorrow it’s Google sign-in, and next month it’s OTP. The context remains the same; only the strategy plugged into it changes.