Skip to content

Strategy Design Pattern (Behavioral)

Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.


Imagine you’re creating a navigation app for casual travelers. One of the primary features is an automatic route planner. A user should be able to enter an address and see the fastest route to their destination displayed on the map.

The first version of the app could only build routes over roads. People traveling by car were ecstatic. But soon, you realize some users prefer walking, while others use public transport or bicycles.

Each time you added a new routing algorithm, the main class of the navigator doubled in size. At some point, the beast became too hard to maintain. Any change to one of the algorithms affected the whole class, increasing the chance of creating an error in already-working code.

The Strategy pattern suggests that you take a class that does something specific in a lot of different ways and extract all of these algorithms into separate classes called strategies.

The original class, called context, must have a field for storing a reference to one of the strategies. The context delegates the work to a linked strategy object instead of executing it on its own.

The context isn’t responsible for selecting an appropriate algorithm for the job. Instead, the client passes the desired strategy to the context. In fact, the context doesn’t know much about strategies; it works with all of them through the same generic interface.

Imagine you have to get to the airport. You can catch a bus, order a cab, or get on a bicycle. These are your transportation strategies. You can choose one of the strategies depending on factors such as budget or time constraints.


  1. Context maintains a reference to one of the concrete strategies and communicates with this object only via the strategy interface.
  2. Strategy interface is common to all concrete strategies. It declares a method the context uses to execute a strategy.
  3. Concrete Strategies implement different variations of an algorithm the context uses.
  4. Client creates a specific strategy object and passes it to the context. The context exposes a setter which lets clients replace the strategy associated with the context at runtime.
classDiagram
    class Context {
        -strategy: Strategy
        +setStrategy(strategy: Strategy)
        +executeStrategy(data)
    }
    class Strategy {
        <<interface>>
        +execute(data)
    }
    class ConcreteStrategyA {
        +execute(data)
    }
    class ConcreteStrategyB {
        +execute(data)
    }

    Context o-- Strategy
    Strategy <|-- ConcreteStrategyA
    Strategy <|-- ConcreteStrategyB
    Client ..> Context
    Client ..> ConcreteStrategyA

# The strategy interface declares operations common to all
# supported versions of some algorithm.
interface RouteStrategy:
method buildRoute(A, B)
# Concrete strategies implement the algorithm while following
# the base strategy interface.
class RoadStrategy implements RouteStrategy:
method buildRoute(A, B):
# Implementation for road routing.
class WalkingStrategy implements RouteStrategy:
method buildRoute(A, B):
# Implementation for walking paths.
# The context maintains a reference to one of the strategy
# objects.
class Navigator:
private field strategy: RouteStrategy
method setStrategy(strategy):
this.strategy = strategy
method buildRoute(A, B):
strategy.buildRoute(A, B)

  • Variant Algorithms: Use the Strategy pattern when you want to use different variants of an algorithm within an object and be able to switch from one algorithm to another during runtime.
  • Similar Classes: Use the Strategy when you have a lot of similar classes that only differ in the way they execute some behavior.
  • Isolate Business Logic: Use the pattern to isolate the business logic of a class from the implementation details of algorithms that may not be as important in the context of that logic.
  • Hide Massive Conditionals: Use the pattern when your class has a massive conditional operator that switches between different variants of the same algorithm.
  1. In the context class, identify an algorithm that’s prone to frequent changes.
  2. Declare the strategy interface common to all variants of that algorithm.
  3. One by one, extract all algorithms into their own classes. They should all implement the strategy interface.
  4. In the context class, add a field for storing a reference to a strategy object.
  5. Clients of the context must associate it with a suitable strategy that matches the way they expect the context to perform its primary job.

Pros:

  • You can swap algorithms used inside an object at runtime.
  • You can isolate the implementation details of an algorithm from the code that uses it.
  • You can replace inheritance with composition.
  • Open/Closed Principle: You can introduce new strategies without having to change the context.

Cons:

  • If you only have a couple of algorithms and they rarely change, there’s no real reason to overcomplicate the program with new classes and interfaces.
  • Clients must be aware of the differences between strategies to be able to select a proper one.
  • A lot of modern programming languages have functional type support that lets you implement different versions of an algorithm inside a set of anonymous functions.
  • Bridge, Strategy, and State have very similar structures based on composition. However, they all solve different problems.
  • Strategy changes the guts of an object, while Decorator changes the skin.
  • Template Method is based on inheritance: it lets you alter parts of an algorithm by extending those parts in subclasses. Strategy is based on composition: you can alter parts of the object’s behavior by supplying it with different strategies.

// Strategy
public interface IStrategy
{
int Execute(int a, int b);
}
// Concrete Strategies
public class AddStrategy : IStrategy
{
public int Execute(int a, int b) => a + b;
}
public class SubtractStrategy : IStrategy
{
public int Execute(int a, int b) => a - b;
}
public class MultiplyStrategy : IStrategy
{
public int Execute(int a, int b) => a * b;
}
// Context
public class Calculator
{
private IStrategy _strategy;
public void SetStrategy(IStrategy strategy)
{
_strategy = strategy;
}
public int Calculate(int a, int b)
{
return _strategy.Execute(a, b);
}
}
// Usage
class Program
{
static void Main()
{
var calc = new Calculator();
calc.SetStrategy(new AddStrategy());
Console.WriteLine(calc.Calculate(5, 3)); // 8
calc.SetStrategy(new MultiplyStrategy());
Console.WriteLine(calc.Calculate(5, 3)); // 15
}
}