Strategy
Intent
Defines a family of algorithms, puts each in its own class, and makes them interchangeable.
Problem
Shipping cost logic for ground, air and express sits in one growing switch statement.
Solution
Extract each algorithm into a strategy with a common interface. The context holds one and delegates. In languages with first-class functions, a strategy can be a function.
Real-world analogy
Getting to the airport: bus, taxi or bike. Same goal, choose by budget and time.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1Context — Context keeps a reference to one strategy and talks to it only through the interface.
- 2Strategy — Strategy declares the interface common to every algorithm variant.
- 3ConcreteStrategies — Concrete Strategies implement the variations of the algorithm.
- 4Context — Each time the context runs the algorithm, it calls execute() on its current strategy.
- 5Client — Client creates a strategy and passes it to the context, and can swap it at runtime.
Try it
Code example
struct ShippingStrategy {
virtual ~ShippingStrategy() = default;
virtual double cost(double kg) const = 0;
};
struct Ground : ShippingStrategy { double cost(double kg) const override { return 5 + kg * 1.2; } };
struct Air : ShippingStrategy { double cost(double kg) const override { return 15 + kg * 3.0; } };
class Order {
public:
explicit Order(std::unique_ptr<ShippingStrategy> s) : strategy(std::move(s)) {}
void setStrategy(std::unique_ptr<ShippingStrategy> s) { strategy = std::move(s); }
double shipping(double kg) const { return strategy->cost(kg); }
private:
std::unique_ptr<ShippingStrategy> strategy;
};
// Order order(std::make_unique<Air>());
// order.shipping(2.0); // 21Applicability
Use Strategy when different variants of an algorithm, switchable at runtime.
Use Strategy when many similar classes differing only in behaviour.
Use Strategy when isolating business logic from algorithm details.
How to implement
- Identify the algorithm that varies
- Declare the strategy interface (or function type)
- Extract each algorithm into a strategy
- Give the context a strategy field and a setter
- Clients choose and inject the strategy
Pros and cons
Pros
- Swap algorithms at runtime
- Isolates algorithm details
- Composition over inheritance
- Open–Closed
Cons
- Overkill for two stable algorithms
- Clients must know the differences between strategies
Relations with other patterns
Check yourself
Checkout must calculate tax with a different algorithm per country, chosen at runtime.
Saved in this browser only. Part of Behavioral patterns (0/11), Hands-on: patterns with live demos (0/5).