Strategy pattern

Also known as: policy pattern

On this page 7

The Strategy pattern is a behavioral design pattern that defines a family of interchangeable algorithms, places each one in its own class or function behind a common interface, and lets client code select or replace the algorithm at run time without changing the code that uses it. In programming architecture it is also called the policy pattern, because each strategy encodes a policy for how a task should be performed.

The pattern was cataloged by the Gang of Four in 1994, and it remains one of the most widely applied ideas in software architecture. Its value lies in separating what varies from what stays stable: the surrounding workflow is written once, while the variable rule, such as a pricing formula, a sorting order or a compression method, can be added, tested and swapped independently.

How the Strategy pattern separates an algorithm from its context

The Strategy pattern works by having a context object hold a reference to a strategy and delegate the variable step to it instead of implementing that step itself. The context knows only the strategy interface, so it never needs conditional branches that check which concrete algorithm is in use.

Three roles make up the classic structure. Each role has a narrow responsibility, which is why the pattern is often cited as a direct application of the Open/Closed Principle: new behavior arrives as a new class, and existing classes remain closed to modification.

ParticipantResponsibilityTypical form in code
Strategy interfaceDeclares the operation every algorithm must provideInterface, abstract class, protocol or function type
Concrete strategyImplements one specific algorithmClass such as FlatRateShipping or a lambda
ContextHolds a strategy and calls it when the step is neededService, controller or domain object
The three participants of the Strategy pattern

The client, or a configuration layer, decides which concrete strategy to inject. This choice can happen once at startup, per request, or even mid-operation, and the context does not care which. That freedom is the core benefit: behavior becomes data that can be passed around like any other value.

Implementation styles across programming languages

The Strategy pattern can be implemented with classes, first-class functions or generics, and the best choice depends on whether the strategy needs state and how the language models behavior. Modern languages have made the lightweight forms common, so many developers use the pattern daily without naming it.

StyleExample languagesBest suited for
Interface and classesJava, C#, TypeScriptStrategies with state, configuration or several methods
First-class functionsPython, JavaScript, KotlinSingle-operation rules without internal state
Compile-time genericsC++ templates, Rust traitsPerformance-critical code with no run-time switching
Enum with behaviorJava enums, Rust enumsA small, closed set of known algorithms
Common ways to express a strategy

A typical example is a checkout service that accepts a ShippingCostStrategy. In Python, passing calculate_cost=express_rate is already a Strategy; in Java, the same idea becomes an interface with an apply(Order order) method. The standard library comparator used by sorting functions is perhaps the most familiar real instance of the pattern.

Compile-time variants trade flexibility for speed. Static dispatch through templates or traits removes the virtual call, but the strategy can no longer be changed while the program runs, which is acceptable only when the choice is known at build time.

The Strategy pattern is distinguished from similar patterns by its intent: choosing among interchangeable algorithms for the same task. Several neighboring patterns share the same class diagram of an interface with multiple implementations, so structure alone does not identify the pattern.

PatternMain intentKey difference from Strategy
State patternChange behavior as internal state changesStates often switch themselves; strategies are chosen from outside
Template methodFix an algorithm skeleton, vary some stepsUses inheritance instead of composition
Command patternEncapsulate a request as an objectRepresents an action to execute, not a way of computing
Decorator patternAdd responsibilities around an objectWraps and extends behavior instead of replacing it
Dependency injectionSupply collaborators from outsideA delivery technique that often carries strategies
How Strategy differs from structurally similar patterns

The comparison with Template method is the most instructive. Both vary part of an algorithm, but Strategy relies on composition over inheritance, so the varying part can be changed per object and at run time, while a subclass in Template method fixes the choice when the object is created.

When to apply the Strategy pattern

The Strategy pattern pays off when a piece of logic has several legitimate variants that are likely to grow and when those variants should be testable in isolation. A reliable warning sign is a long switch or if-else chain that selects behavior by type code and is edited every time a new case appears.

SituationRecommended choiceReason
Two fixed variants, unlikely to changeSimple conditionalAbstraction would add cost without benefit
Growing list of algorithmsStrategy interfaceNew cases arrive without editing existing code
Behavior chosen by configuration or tenantStrategy with a registry or factorySelection logic stays in one place
Variants differ in one small functionFunction parameterLightweight form avoids class boilerplate
Behavior depends on object lifecycleState patternTransitions belong to the object itself
Decision guide for introducing a strategy

Typical domains include payment and tax calculation, retry and backoff policies, routing algorithms, validation rules, serialization formats and feature-flagged experiments. In each case, the stable workflow lives in the context, and each rule gets its own unit tests.

Trade-offs and common mistakes

The main cost of the Strategy pattern is added indirection: more types, more files and a call path that a reader must trace through an interface. Experienced teams accept that cost only where variation is real, guided by the YAGNI principle rather than by a desire to make every rule pluggable.

  • Premature abstraction: wrapping a single algorithm in an interface “for the future” adds complexity that may never be repaid.
  • Leaky interfaces: if the context must know which strategy it holds, for example through type checks, the pattern has been defeated.
  • Bloated strategy signatures: passing many parameters that only some strategies use signals a poorly chosen abstraction.
  • Hidden selection logic: scattering the choice of strategy across the codebase recreates the conditionals the pattern was meant to remove.
  • Shared mutable state: a stateful strategy reused across threads can produce subtle concurrency bugs; prefer stateless strategies or one instance per use.

Applied with judgment, the pattern supports the SOLID principles, especially single responsibility and open/closed, and it fits naturally with clean and hexagonal architectures, where business rules are injected as policies at the edges of the system.

A non-technical view

Think of a navigation app that asks whether you want the fastest route, the shortest route or a route without tolls. The app itself does not change. Only the rule for choosing the route changes, and you can switch it with one tap.

The Strategy pattern is the same idea inside software. A program keeps its main job fixed and plugs in a different method for one step whenever needed. This keeps the program tidy, because adding a new method means adding a new piece, not rewriting the old ones.

A concrete example

An online retailer sells to customers in twelve countries, and each country has its own shipping cost rules: flat rates in some, weight-based tables in others and free delivery above a threshold in a few. The original checkout code contained a 400-line conditional block that developers edited for every new market, and each change risked breaking existing countries.

The team introduced a ShippingCostStrategy interface with one method that takes an order and returns a price. Each country received its own concrete strategy, and a small registry selected the right one from the delivery address. The checkout service now simply calls the injected strategy.

When the company expanded to three new markets, developers added three small classes with their own tests and changed nothing in the checkout flow. Regression defects in shipping calculation dropped to zero over the next two releases, and code reviews became shorter because each change touched only one isolated rule.