Define a family of interchangeable algorithms, put each one behind the same interface and let the code that uses them pick one at runtime.
Strategy takes a decision that has several interchangeable answers —how to pick, how to price, how to sort— and moves each answer into its own object behind a common interface. The code that needs the decision keeps a reference to «some strategy» and calls it, without knowing which one it got. Adding a new rule means adding a class, not editing a growing if/else that everyone touches.
The problem
A situation where the obvious design starts to hurt.
You maintain the helpdesk of an online shop. Every incoming ticket has to be assigned to an agent, and each support queue wants a different rule. The general queue shares work evenly, one agent after another. Billing sends each ticket to whoever has the fewest open tickets, because those cases take long. The international queue wants an agent who speaks the customer's language.
Today all of that lives in one assign() function with a switch on the queue type. The round-robin branch needs a cursor that survives between calls, so it's a module-level variable. The language branch copies half of the least-loaded branch to break ties. Product has just asked for a fourth rule —VIP customers go to senior agents— and a fifth is rumoured. Every change touches the same function, the tests for one rule break when someone edits another, and nobody can try a new rule on a single queue without a deploy that affects all of them.
The solution
What the pattern proposes.
Pull each rule out into its own class with one method, pick(ticket, agents), and make all of them implement the same AssignmentPolicy interface. Round robin keeps its cursor as a private field, where it belongs. The language rule doesn't copy the least-loaded logic: it narrows the list to speakers and delegates to another policy it receives in its constructor.
The TicketRouter —the context— holds a reference to a policy and calls it when a ticket arrives. It still owns everything that's the same for all rules: rejecting the ticket if nobody is available, increasing the agent's counter, logging. Which policy each queue uses is decided once, where the queue is configured. The VIP rule becomes a new class and one line of configuration; no existing rule is edited, and each one is tested on its own.
An everyday analogy
The same idea, outside software.
Think of a football coach before a match. The team, the stadium and the rules don't change, but the game plan does: press high against a slow defence, sit deep against a fast counter-attack, keep possession when you're ahead. The coach doesn't rebuild the team for each opponent; they hand the players a different plan. The players (the context) execute whatever plan they've been given, and a new plan can be drawn up without retraining anyone.
Structure
The pieces and how they relate.
Participants
- AssignmentPolicy (strategy)
- The interface every rule implements: one method that receives the ticket and the candidates and returns the chosen agent, or nothing.
- RoundRobin, LeastLoaded, SameLanguage (concrete strategies)
- One rule each, with whatever state it needs. They don't know about each other, except when one deliberately wraps another, as SameLanguage does.
- TicketRouter (context)
- Keeps a reference to a policy and calls it. Owns the logic that's common to every rule: failing when nobody is free, updating counters, logging.
- Queue setup (client)
- Decides which policy each queue uses, usually from configuration, and hands it to the router. It's the only place that knows the concrete classes.
Pseudocode
The solution to the scenario, language-neutral.
interface AssignmentPolicy
pick(ticket, agents) -> agent or nothing
class RoundRobin implements AssignmentPolicy
next = 0
pick(ticket, agents)
agent = agents[next mod size(agents)]
next = next + 1
return agent
class LeastLoaded implements AssignmentPolicy
pick(ticket, agents)
return the agent with the fewest open tickets
class SameLanguage implements AssignmentPolicy
fallback: AssignmentPolicy
pick(ticket, agents)
speakers = agents who speak ticket.language
return fallback.pick(ticket, speakers if any, else agents)
class TicketRouter
policy: AssignmentPolicy
assign(ticket, agents)
agent = policy.pick(ticket, agents)
if there is no agent: fail "nobody available"
agent.openTickets = agent.openTickets + 1
return agent
// set up once per queue, from its configuration
generalQueue.router = new TicketRouter(new RoundRobin())
billingQueue.router = new TicketRouter(new LeastLoaded())
intlQueue.router = new TicketRouter(new SameLanguage(new LeastLoaded()))The code
The same solution in TypeScript, Python and PHP.
type Agent = { id: string; languages: string[]; openTickets: number };
type Ticket = { id: string; language: string };
/** The strategy: how a queue picks who takes the next ticket. */
interface AssignmentPolicy {
pick(ticket: Ticket, agents: Agent[]): Agent | undefined;
}
class RoundRobin implements AssignmentPolicy {
private next = 0; // each policy keeps its own state
pick(_ticket: Ticket, agents: Agent[]) {
const agent = agents[this.next % agents.length];
this.next++;
return agent;
}
}
class LeastLoaded implements AssignmentPolicy {
pick(_ticket: Ticket, agents: Agent[]) {
return agents.reduce<Agent | undefined>(
(best, a) => (!best || a.openTickets < best.openTickets ? a : best),
undefined,
);
}
}
/** Narrows to agents who speak the ticket's language, then delegates. */
class SameLanguage implements AssignmentPolicy {
constructor(private fallback: AssignmentPolicy) {}
pick(ticket: Ticket, agents: Agent[]) {
const speakers = agents.filter((a) => a.languages.includes(ticket.language));
return this.fallback.pick(ticket, speakers.length ? speakers : agents);
}
}
/** The context: knows when to assign, not how to choose. */
class TicketRouter {
constructor(private policy: AssignmentPolicy) {}
setPolicy(policy: AssignmentPolicy) {
this.policy = policy;
}
assign(ticket: Ticket, agents: Agent[]): string {
const agent = this.policy.pick(ticket, agents);
if (!agent) throw new Error(`Nobody available for ticket ${ticket.id}`);
agent.openTickets++;
return agent.id;
}
}
// Each queue chooses its policy in its configuration, not in an if.
const general = new TicketRouter(new RoundRobin());
const billing = new TicketRouter(new LeastLoaded());
const international = new TicketRouter(new SameLanguage(new LeastLoaded()));from dataclasses import dataclass
from typing import Protocol
@dataclass
class Agent:
id: str
languages: list[str]
open_tickets: int = 0
@dataclass
class Ticket:
id: str
language: str
class AssignmentPolicy(Protocol):
"""The strategy: how a queue picks who takes the next ticket."""
def pick(self, ticket: Ticket, agents: list[Agent]) -> Agent | None: ...
class RoundRobin:
def __init__(self) -> None:
self._next = 0 # each policy keeps its own state
def pick(self, ticket: Ticket, agents: list[Agent]) -> Agent | None:
if not agents:
return None
agent = agents[self._next % len(agents)]
self._next += 1
return agent
class LeastLoaded:
def pick(self, ticket: Ticket, agents: list[Agent]) -> Agent | None:
return min(agents, key=lambda a: a.open_tickets, default=None)
class SameLanguage:
"""Narrows to agents who speak the ticket's language, then delegates."""
def __init__(self, fallback: AssignmentPolicy) -> None:
self._fallback = fallback
def pick(self, ticket: Ticket, agents: list[Agent]) -> Agent | None:
speakers = [a for a in agents if ticket.language in a.languages]
return self._fallback.pick(ticket, speakers or agents)
class TicketRouter:
"""The context: knows when to assign, not how to choose."""
def __init__(self, policy: AssignmentPolicy) -> None:
self.policy = policy
def assign(self, ticket: Ticket, agents: list[Agent]) -> str:
agent = self.policy.pick(ticket, agents)
if agent is None:
raise LookupError(f"Nobody available for ticket {ticket.id}")
agent.open_tickets += 1
return agent.id
# Each queue chooses its policy in its configuration, not in an if.
general = TicketRouter(RoundRobin())
billing = TicketRouter(LeastLoaded())
international = TicketRouter(SameLanguage(LeastLoaded()))<?php
final class Agent
{
public function __construct(
public readonly string $id,
/** @var string[] */
public readonly array $languages,
public int $openTickets = 0,
) {}
}
final class Ticket
{
public function __construct(public readonly string $id, public readonly string $language) {}
}
/** The strategy: how a queue picks who takes the next ticket. */
interface AssignmentPolicy
{
/** @param Agent[] $agents */
public function pick(Ticket $ticket, array $agents): ?Agent;
}
final class RoundRobin implements AssignmentPolicy
{
private int $next = 0; // each policy keeps its own state
public function pick(Ticket $ticket, array $agents): ?Agent
{
if ($agents === []) {
return null;
}
$agent = $agents[$this->next % count($agents)];
$this->next++;
return $agent;
}
}
final class LeastLoaded implements AssignmentPolicy
{
public function pick(Ticket $ticket, array $agents): ?Agent
{
$best = null;
foreach ($agents as $agent) {
if ($best === null || $agent->openTickets < $best->openTickets) {
$best = $agent;
}
}
return $best;
}
}
/** Narrows to agents who speak the ticket's language, then delegates. */
final class SameLanguage implements AssignmentPolicy
{
public function __construct(private AssignmentPolicy $fallback) {}
public function pick(Ticket $ticket, array $agents): ?Agent
{
$speakers = array_values(array_filter(
$agents,
fn (Agent $a) => in_array($ticket->language, $a->languages, true),
));
return $this->fallback->pick($ticket, $speakers ?: $agents);
}
}
/** The context: knows when to assign, not how to choose. */
final class TicketRouter
{
public function __construct(private AssignmentPolicy $policy) {}
public function setPolicy(AssignmentPolicy $policy): void
{
$this->policy = $policy;
}
public function assign(Ticket $ticket, array $agents): string
{
$agent = $this->policy->pick($ticket, $agents);
if ($agent === null) {
throw new RuntimeException("Nobody available for ticket {$ticket->id}");
}
$agent->openTickets++;
return $agent->id;
}
}
// Each queue chooses its policy in its configuration, not in an if.
$general = new TicketRouter(new RoundRobin());
$billing = new TicketRouter(new LeastLoaded());
$international = new TicketRouter(new SameLanguage(new LeastLoaded()));When to use it
Situations where it pays off.
A function has an if/else or a switch that picks between variants of the same calculation.
Each branch becomes a class you can read, test and change in isolation, and the function goes back to doing one thing.
The variant has to be chosen at runtime: per customer, per tenant, from a feature flag or from configuration.
The context receives a strategy object; changing behaviour is passing a different object, with no deploy that touches the others.
Several rules need their own state or dependencies (a cursor, a cache, an external client).
That state lives inside the strategy that needs it instead of floating around as shared variables.
You want to try a new rule on a small slice of traffic.
Plug the new strategy into one queue or one percentage of requests, compare, and remove it if it doesn't pay off.
How to implement it
Steps to introduce it in existing code.
Find the decision that varies and name it as a question: «who takes this ticket?». That question becomes the interface method.
Write the interface with the smallest signature that every variant can work with. Pass in data, not the whole context object.
Move each branch of the conditional into its own class that implements the interface. Bring along the state that only that branch used.
Give the context a field of the interface type, set it in the constructor and replace the conditional with a single call to it.
Move the choice of strategy to where the configuration lives (a factory, the dependency container, the queue's settings).
Test each strategy on its own with a handful of agents and tickets, then one test for the context with a fake strategy.
Pros and cons
What you gain and what you pay.
Pros
- Adding a rule means adding a class: existing rules and the context stay untouched (open/closed).
- Each rule is small and can be tested without setting up the rest of the system.
- Behaviour can change at runtime or per tenant without branching in the calling code.
- Strategies can be composed: a filter that delegates to another policy avoids copying logic.
Cons
- With two stable variants that never change, the interface and the extra classes are more code to read for no gain.
- Whoever configures the context has to know which strategies exist and how they differ.
- All strategies share one signature; a rule that needs extra data forces you to widen it for everyone or to inject that data elsewhere.
- In languages with first-class functions, a whole class hierarchy can be overkill where a function would do.
Relations with other guides
Patterns it's often confused or combined with.
- State Pattern: Explicit State Machines Without the Switch Statements
Same shape, different intent: in State the object swaps its own behaviour as its internal state changes; in Strategy someone from outside chooses the behaviour.
- Template Method: A Fixed Algorithm With Steps Subclasses Fill In
Template Method varies steps through inheritance and fixes the skeleton at compile time; Strategy varies the whole algorithm through composition and can change at runtime.
- Decorator: Add Behaviour by Wrapping, the Way Middleware Does
Decorator changes an object's skin by wrapping it; Strategy changes its guts. SameLanguage above is a small decorator around another strategy.
- Replace Conditional with Polymorphism: One Class per Case
The refactoring that usually leads to Strategy: each branch of the conditional becomes an implementation.
Common questions
Short answers to the usual doubts.
Do I need classes, or is a function enough?
In TypeScript, Python or modern PHP a function with the right signature is a perfectly good strategy: type AssignmentPolicy = (ticket, agents) => Agent | undefined. Use classes when the strategy has state (the round-robin cursor) or dependencies, or when your team's codebase is built around interfaces. The pattern is the idea, not the class diagram.
How is Strategy different from dependency injection?
Dependency injection is how the context receives its collaborators; Strategy is a reason to have a collaborator in the first place. You'll often inject the strategy, but you can also create it on the spot from configuration.
Who should choose the strategy?
Whoever has the information to choose: usually the configuration or a small factory. If the context ends up with a switch to pick its own strategy, you've moved the conditional, not removed it.
How do I bring it up in an interview without sounding like a textbook?
Start from the pain: «this switch was growing with every new rule and each change risked breaking the others». Then say what you did —one class per rule behind an interface, chosen by configuration— and what it bought you: a new rule in an afternoon, tested on its own.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Notification serviceSolve the exercise