Skip to content

Strategy: swap the rule without touching who uses it

The Strategy pattern explained with a helpdesk that assigns tickets: one interface per decision, one class per rule, chosen by configuration.

9 min readDesign patternBehavioural

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.

The router holds one assignment policy; each policy implements the same interface and can be swapped at configuration time.Queue setup creates TicketRouter (configures). TicketRouter has a AssignmentPolicy. RoundRobin implements AssignmentPolicy. LeastLoaded implements AssignmentPolicy. SameLanguage implements AssignmentPolicy. SameLanguage calls LeastLoaded.Queue setupchooses a policyTicketRouterassign(ticket,agents)«interface»AssignmentPolicypick(ticket, agents)RoundRobinkeeps a cursorLeastLoadedfewest open ticketsSameLanguagefilters, thendelegatesconfigures
The router holds one assignment policy; each policy implements the same interface and can be swapped at configuration time.

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()));

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.

  1. Find the decision that varies and name it as a question: «who takes this ticket?». That question becomes the interface method.

  2. Write the interface with the smallest signature that every variant can work with. Pass in data, not the whole context object.

  3. Move each branch of the conditional into its own class that implements the interface. Bring along the state that only that branch used.

  4. Give the context a field of the interface type, set it in the constructor and replace the conditional with a single call to it.

  5. Move the choice of strategy to where the configuration lives (a factory, the dependency container, the queue's settings).

  6. 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.

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.

Next guide9 of 10 · Behavioral patternsTemplate Method: A Fixed Algorithm With Steps Subclasses Fill InRead the next one