Strategy
What you will learn on this page
Section titled “What you will learn on this page”- The problem Strategy solves, shown before the pattern is named: one job that can be done in several ways, chosen while the program runs.
- How to decide which data members belong to the class that needs the job done and which belong to one way of doing it.
- The parts of the pattern (the context, the strategy, and the concrete strategies) and how they map to C++ types.
- Who owns a strategy, how long it lives, and what happens to its state when it is replaced.
- Three ways to write a strategy in C++: a virtual interface, a
std::function, and a template parameter, and how to choose. - When not to use Strategy: a
switchor a plain function is often the better design.
The problem
Section titled “The problem”A company’s support desk receives tickets from customers and gives each one to an agent. Different teams want tickets handed out differently.
Requirements:
- FR-1 Each incoming ticket goes to exactly one available agent.
- FR-2 A team chooses how tickets are assigned:
- round robin: agents take turns;
- least busy: the agent with the fewest open tickets, the earliest in the list on a tie;
- skill match: the least busy agent who has the skill the ticket needs (“billing”, “network”); if no such agent is available, the least busy agent of all.
- FR-3 A team lead can change the rule while the desk is running. Tickets already assigned keep their agent.
- FR-4 If nobody is available, the ticket is not assigned; the caller keeps it and tries again later.
- FR-5 An agent’s count of open tickets goes up by one when they are given a ticket and down by one when they resolve one.
The data is simple. An agent has a name, a list of skills, whether they are available, and how many tickets they have open. A ticket has an id, a subject, and the skill it needs:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Plain data, with no rules of its own. Every desk owns its agents; a// ticket is only borrowed while it is being assigned.struct Agent { std::string name; std::vector<std::string> skills; // e.g. "billing", "network" bool available = true; // false while offline: no rule may choose them int open_tickets = 0; // tickets given to them and not yet resolved};
struct Ticket { int id; std::string subject; std::string skill; // the skill it needs; empty if any agent will do};Where Strategy shows up in requirements. Listen for wording like
“teams choose how…”, “can be changed while running”, “customers
on the premium plan get a different rule”, or “the partner team
will add their own method”. Each says that one job has several
interchangeable ways of being done, and that the choice is made outside
the code that needs the job done. In code, the signal is a switch on a
“mode” or “kind” value that keeps growing, especially when some data
members are used by only one case. Strategy is one of the patterns
that comes up most often in application design, but a switch or a
function parameter is enough more often still.
The straightforward solution
Section titled “The straightforward solution”The obvious design keeps every rule inside the desk and picks one with a
switch:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The three ways of choosing an agent, as names.enum class Rule { round_robin, least_busy, skill_match };
// Every rule lives inside the desk, selected by a switch.// The desk owns its agents (moved in by the constructor) and remembers// which Rule is in force. Adding a rule means editing this class.class HelpDesk final {public: HelpDesk(std::vector<Agent> agents, Rule rule);
// Returns the chosen agent's name, or nullopt if nobody is available. std::optional<std::string> assign(const Ticket& ticket); void set_rule(Rule rule); void set_available(std::string_view agent_name, bool available); void resolve(std::string_view agent_name); std::span<const Agent> agents() const;
private: std::vector<Agent> agents_; Rule rule_; // Round robin's memory of whose turn it is. It sits in the desk even // while another rule is in force, and is stale when round robin returns. std::size_t next_ = 0; // used only when rule_ is round_robin};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each case works out `chosen`, the index of the agent to get the ticket// (left empty if nobody can), and one shared line at the end records it.std::optional<std::string> HelpDesk::assign(const Ticket& ticket) { std::optional<std::size_t> chosen; // starts empty: nobody chosen yet switch (rule_) { case Rule::round_robin: // Try each agent at most once, starting with the one whose turn // it is. `% agents_.size()` wraps past the end back to index 0: // with 3 agents and next_ = 2, the tries are 2, 0, 1. for (std::size_t step = 0; step < agents_.size(); ++step) { const std::size_t i = (next_ + step) % agents_.size(); if (agents_[i].available) { chosen = i; next_ = (i + 1) % agents_.size(); // the turn after this agent's break; // leaves the for loop only } } break; // leaves the switch case Rule::least_busy: chosen = least_busy(agents_); break; case Rule::skill_match: // The least busy agent with the skill; if there is none, anyone. chosen = least_busy(agents_, ticket.skill); if (!chosen) { chosen = least_busy(agents_); } break; } return record_assignment(agents_, chosen);}The two helpers it calls are shared by every version on this page.
least_busy finds the least busy available agent, optionally with a
skill. record_assignment gives the ticket to the chosen agent and adds
one to their count:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// True if `skill` is in agent.skills. std::string_view is a read-only view// of some text, so a literal like "billing" can be passed without copying.bool has_skill(const Agent& agent, std::string_view skill);
// std::span<const Agent> is a read-only view of agents stored next to each// other, such as a std::vector<Agent>, which converts to it without a copy.// The `= {}` default makes `skill` empty, meaning "any skill".
// The index of the available agent with the fewest open tickets, the// earliest in the list on a tie. If `skill` is not empty, only agents with// that skill count. Returns nullopt if no agent qualifies.std::optional<std::size_t> least_busy(std::span<const Agent> agents, std::string_view skill = {});
// Gives the ticket to agents[chosen], or does nothing if chosen is empty.// Returns the agent's name. Throws std::logic_error if chosen is out of// range or names an unavailable agent: a rule must never do that.// This is the only function that changes an agent's count, and it checks// the rule's answer before it changes anything.std::optional<std::string> record_assignment(std::vector<Agent>& agents, std::optional<std::size_t> chosen);This version works, and a test later on this page checks that the final
design assigns the same agents as this switch, rule by rule. Its limits show up when you
look at who owns what:
next_is not the desk’s data. It records whose turn it is, which only round robin cares about. When the rule is least busy,next_is a member that means nothing but still has to be kept, copied, and explained. When the team switches back to round robin, it resumes from a stale turn.- Every new rule edits the desk. A rule “by customer tier” means a
new enumerator, a new
case, and probably new members that only thatcaseuses. The desk’s code, and its tests, change for every rule any team invents. - A rule cannot be tested on its own. To check round robin’s wrap-around, you must build a desk, set the rule, and assign several tickets through it.
- A rule cannot come from outside. If another team wants a rule of
their own, they must edit
HelpDesk.
Step 1: sort the data and the functions
Section titled “Step 1: sort the data and the functions”Before naming any pattern, ask of each data member and each function: who needs it, and for which rule?
| Data member | Who uses it | Where it belongs |
|---|---|---|
agents_ |
every rule reads it; the desk changes it | the desk: it owns the agents and their counts |
rule_ |
the desk, to pick a branch | replaced by “the rule object the desk holds” |
next_ |
round robin only | round robin: it is that rule’s own state |
| Function or need | Who needs it | Where it belongs |
|---|---|---|
| choose an agent for a ticket | the desk, through whichever rule | one function per rule, same signature |
| give the ticket and count it (FR-5) | the desk, for every rule | the desk: the count must be right whatever the rule |
| check the rule chose sensibly | the desk | the desk: it must not trust every rule blindly |
| make an agent unavailable, resolve | the team lead, the agent | the desk |
Two decisions fall out of these tables:
- A rule chooses; the desk assigns. If each rule also updated the counts, every rule would have to get FR-5 right, and one buggy rule could break the counts for everyone. So a rule only returns which agent, and the desk does the rest, in one place.
- Each rule’s state lives in the rule.
next_moves into round robin. When round robin is not in use, its state does not exist.
The pattern
Section titled “The pattern”The Strategy pattern has three roles, plus the code that picks one:
| Role | What it does | In this example |
|---|---|---|
| Context | Needs the job done; holds one strategy and calls it | HelpDesk |
| Strategy | The interface every way of doing the job shares | AssignmentRule, with choose |
| Concrete strategy | One way of doing the job, with its own state | RoundRobin, LeastBusy, SkillMatch |
| Client | Picks a concrete strategy and gives it to the context | main (in a real system: settings) |
interface (abstract class) AssignmentRule
the strategy
Member functions
virtual std::optional<std::size_t> choose(const Ticket& ticket, std::span<const Agent> agents) = 0;
class RoundRobin final
implements AssignmentRule
Data members
std::size_t next_ = 0;whose turn it is
Member functions
std::optional<std::size_t> choose(const Ticket& ticket, std::span<const Agent> agents) override;
class LeastBusy final
implements AssignmentRule; no state
Member functions
std::optional<std::size_t> choose(const Ticket& ticket, std::span<const Agent> agents) override;
class SkillMatch final
implements AssignmentRule; no state
Member functions
std::optional<std::size_t> choose(const Ticket& ticket, std::span<const Agent> agents) override;
class HelpDesk final
the context
Data members
std::vector<Agent> agents_;std::unique_ptr<AssignmentRule> rule_;owned; never null
Member functions
HelpDesk(std::vector<Agent> agents, std::unique_ptr<AssignmentRule> rule);std::optional<std::string> assign(const Ticket& ticket);void set_rule(std::unique_ptr<AssignmentRule> rule);void set_available(std::string_view agent_name, bool available);void resolve(std::string_view agent_name);std::span<const Agent> agents() const;
The outline leaves out AssignmentRule’s virtual destructor and its
protected constructor and copy operations; they are in the code below.
Text description of the diagram
A solid arrow means “owns”, a dashed arrow means “uses”, and a thick arrow means “implements”. HelpDesk, the context, has a solid arrow labelled “owns 1” to the AssignmentRule strategy interface and a solid arrow labelled “owns 0..*” to Agent, which is plain data. RoundRobin (which holds next_), LeastBusy, and SkillMatch each have a thick arrow labelled “implements” to AssignmentRule. AssignmentRule has a dashed arrow labelled “reads” to Agent. main, the client, has a dashed arrow labelled “creates” to RoundRobin and a dashed arrow labelled “uses” to HelpDesk. No arrow points from HelpDesk to a concrete rule.
Diagram source (Mermaid)
flowchart TB
MN["main<br/>the client"] -.->|creates| RR
MN -.->|uses| HD
HD["HelpDesk<br/>context"] -->|owns 1| AR["AssignmentRule<br/>strategy interface"]
HD -->|owns 0..*| AG["Agent<br/>data"]
RR["RoundRobin<br/>next_"] ==>|implements| AR
LB["LeastBusy"] ==>|implements| AR
SM["SkillMatch"] ==>|implements| AR
AR -.->|reads| AGThe C++ implementation
Section titled “The C++ implementation”The strategy interface
Section titled “The strategy interface”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The strategy: one way of choosing who gets a ticket.// An interface: it has no data, and its one function is pure virtual// (`= 0`), so every concrete rule must supply its own choose().class AssignmentRule {public: // virtual, so that the desk's std::unique_ptr<AssignmentRule> destroys // the real rule (say, a RoundRobin) correctly. virtual ~AssignmentRule() = default;
// Returns the index in `agents` of an available agent, or nullopt if // nobody can take the ticket. Not const: a rule may remember earlier // choices. The agents are read-only: a rule chooses, it does not assign. virtual std::optional<std::size_t> choose(const Ticket& ticket, std::span<const Agent> agents) = 0;
protected: // protected: only a derived rule can create the base part, so nobody // can make a bare AssignmentRule. AssignmentRule() = default; // Only derived classes may copy or move the base part (no slicing). AssignmentRule(const AssignmentRule&) = default; AssignmentRule& operator=(const AssignmentRule&) = default;};Each choice in this signature is deliberate:
- It returns an index, not an agent. The rule says which; the
desk assigns. An
std::optionalsays “nobody” without a magic value such as-1. - It takes
std::span<const Agent>. A rule sees every agent but cannot change one. That is how the type system enforces “a rule chooses; the desk assigns”. - It takes the whole
Ticket. Today only skill match reads it. If a later rule needs the customer’s plan,Ticketgains a field and the interface does not change. - It is not
const. Round robin must remember whose turn it is, so choosing changes it. Aconstfunction would force that state into amutablemember, which hides the fact that callingchoosehas an effect. - Copying is protected. As on the earlier interface pages, this stops code from copying only the base part of a rule (slicing).
The concrete strategies
Section titled “The concrete strategies”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The three concrete strategies. Each is `final` (nothing derives from it),// and `override` makes the compiler check that choose() matches the// interface exactly.
// Agents take turns, skipping anyone who is unavailable.class RoundRobin final : public AssignmentRule {public: std::optional<std::size_t> choose(const Ticket& ticket, std::span<const Agent> agents) override;
private: std::size_t next_ = 0; // whose turn it is: this rule's own state};
// The available agent with the fewest open tickets (the earliest in the// list on a tie). It has no state: it looks only at the agents.class LeastBusy final : public AssignmentRule {public: std::optional<std::size_t> choose(const Ticket& ticket, std::span<const Agent> agents) override;};
// The least busy agent with the ticket's skill; anyone least busy if no// agent with that skill is available. A ticket with no skill can go to// anyone available.class SkillMatch final : public AssignmentRule {public: std::optional<std::size_t> choose(const Ticket& ticket, std::span<const Agent> agents) override;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The ticket does not matter to round robin. Writing its name as a comment,// /*ticket*/, documents the parameter without an "unused" warning.// Tries each agent at most once, starting at next_ and wrapping round the// end of the list with %. The first available agent is chosen, and the turn// moves to the one after them. If nobody is available, it returns nullopt// and next_ is unchanged. (With no agents at all, the loop never runs, so// there is no % by zero.)std::optional<std::size_t> RoundRobin::choose(const Ticket& /*ticket*/, std::span<const Agent> agents) { for (std::size_t step = 0; step < agents.size(); ++step) { const std::size_t i = (next_ + step) % agents.size(); // step places after next_ if (agents[i].available) { next_ = (i + 1) % agents.size(); // next time, start after this agent return i; // a std::size_t converts to std::optional<std::size_t> holding it } } return std::nullopt;}
// All the work is in the shared helper; this class just names the choice.
std::optional<std::size_t> LeastBusy::choose(const Ticket& /*ticket*/, std::span<const Agent> agents) { return least_busy(agents);}
// The `if` declares `skilled` (the optional result) and tests it in one// go: the condition is true if it holds an index. If no available agent// has the skill, fall back to the least busy available agent of all.std::optional<std::size_t> SkillMatch::choose(const Ticket& ticket, std::span<const Agent> agents) { if (const auto skilled = least_busy(agents, ticket.skill)) { return skilled; } return least_busy(agents);}How this code works: RoundRobin::choose
next_ is the index of the agent whose turn it is. Each call tries the
agents in turn order, at most once each, and picks the first available one.
- The candidate on each step is
(next_ + step) % agents.size().%is the remainder after division, so counting past the last index wraps back to 0. With 3 agents andnext_= 2, the steps try 2, 0, 1. - The first available candidate wins.
next_becomes the index after them (again wrapped with%), and the index is returned. - Nobody available. After
agents.size()steps every agent has been tried once; the loop ends,std::nulloptis returned, andnext_is left as it was.
Here is the first test further down this page, with Asha, Ben, and Chen at indexes 0, 1, and 2:
| Call | next_ before |
Ben available? | Tries | Returns | next_ after |
|---|---|---|---|---|---|
| 1 | 0 | yes | 0 | 0 (Asha) | 1 |
| 2 | 1 | no | 1, 2 | 2 (Chen) | 0 |
| 3 | 0 | no | 0 | 0 (Asha) | 1 |
LeastBusy and SkillMatch keep no state, so they give the same answer
for the same agents every time. SkillMatch first asks for the least busy
agent with the ticket’s skill, and only if there is none asks again with
no skill, which means anyone available.
Each rule is a few lines, and each can be tested with a plain
std::vector<Agent> and no desk at all. next_ now lives in the only
class that uses it.
The context
Section titled “The context”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The context: it owns the agents and one rule, and knows nothing about// how any particular rule chooses.class HelpDesk final {public: // Throws std::invalid_argument if rule is null. HelpDesk(std::vector<Agent> agents, std::unique_ptr<AssignmentRule> rule);
// Returns the name of the agent who now has the ticket, or nullopt if // nobody is available (the caller keeps the ticket and tries later). std::optional<std::string> assign(const Ticket& ticket);
// Tickets already assigned keep their agent. Throws // std::invalid_argument if rule is null. void set_rule(std::unique_ptr<AssignmentRule> rule);
// Both throw std::out_of_range for an unknown name; resolve throws // std::logic_error if the agent has no open tickets. void set_available(std::string_view agent_name, bool available); void resolve(std::string_view agent_name);
// A read-only view of the desk's own agents, not a copy. std::span<const Agent> agents() const;
private: std::vector<Agent> agents_; // The desk owns its rule: when it is replaced, or the desk is // destroyed, the rule is deleted automatically. std::unique_ptr<AssignmentRule> rule_; // never null};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// checked() is a small helper earlier in this file: it throws// std::invalid_argument if the pointer is null, and otherwise hands the// same pointer back. std::move passes ownership along each step: from the// parameter into checked(), and from there into the member.HelpDesk::HelpDesk(std::vector<Agent> agents, std::unique_ptr<AssignmentRule> rule) : agents_{std::move(agents)}, rule_{checked(std::move(rule))} {}
// The whole strategy pattern in one line. rule_->choose(...) is a virtual// call: it runs the current rule's choose(), whichever class that is. The// agents_ vector is passed as a read-only span, so the rule cannot change// it. record_assignment then checks the choice and updates the count.std::optional<std::string> HelpDesk::assign(const Ticket& ticket) { return record_assignment(agents_, rule_->choose(ticket, agents_));}
// checked() runs first, so a null rule throws before rule_ is touched and// the old rule stays. Otherwise, assigning to rule_ deletes the old rule// (and any state it had, such as round robin's turn).void HelpDesk::set_rule(std::unique_ptr<AssignmentRule> rule) { rule_ = checked(std::move(rule));}assign is one line: ask the rule, then record the result.
record_assignment (shown earlier) checks the rule’s answer, so a rule
that returns an index out of range, or an agent who is not available,
is refused with std::logic_error instead of corrupting the counts.
Ownership and lifetime
Section titled “Ownership and lifetime”| Object | Owner | Lives |
|---|---|---|
| The agents | HelpDesk, by value in a std::vector |
as long as the desk |
| The current rule | HelpDesk, through std::unique_ptr |
until set_rule replaces it, or the desk is destroyed |
| Each ticket | the caller | the rule and the desk only borrow it during assign |
Why std::unique_ptr? The desk is the only user of its rule, and
the rule’s state (round robin’s turn) belongs with that desk. Two other
choices are possible, and both are worse here:
- A reference,
AssignmentRule& rule_. The desk would not own the rule, so the caller must keep it alive for as long as the desk uses it. FR-3’sset_rulewould also be awkward, because a reference cannot be changed to refer to something else. std::shared_ptr<AssignmentRule>. Two desks could then share one round-robin rule, and its turn counter would mix their agents’ indexes. Shared ownership is usually right only for a rule with no state, and then a plain value or a function is simpler still.
What happens to a rule’s state when it is replaced? set_rule
destroys the old rule. If a team switches from round robin to least
busy and back, the new RoundRobin starts with the first agent again.
That is acceptable here; if it were not, the desk would keep both rules
and switch between them rather than recreate them.
set_rule during assign? Not possible in this single-threaded
example: assign calls choose and returns before anything else runs.
If several threads used one desk, assign and set_rule would need a
mutex; this example does not try to be thread-safe.
Trace: one morning at the desk
Section titled “Trace: one morning at the desk”maincreates the desk with Asha (billing), Ben (network), and Chen (billing, network), and aRoundRobinrule → all counts 0;next_= 0.- Tickets 1, 2, 3 arrive. Round robin chooses indexes 0, 1, 2 → Asha 1,
Ben 1, Chen 1;
next_= 0. - Ben goes offline, and the team lead calls
set_rulewith aSkillMatch→ theRoundRobinis destroyed; counts unchanged. - Ticket 4 needs billing. Asha and Chen have it, both with 1 ticket; Asha is earlier → Asha 2.
- Ticket 5 needs network. Ben is offline, so only Chen qualifies → Chen 2.
- Ticket 6 needs no skill. Asha and Chen both have 2; Asha is earlier → Asha 3.
- Everyone goes offline. Ticket 7 →
choosereturnsnullopt, nothing changes, andassignreturnsnullopt(FR-4).
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// team() returns Asha (billing), Ben (network), and Chen (both).// std::make_unique<RoundRobin>() creates the rule and hands its// ownership to the desk.HelpDesk desk{team(), std::make_unique<RoundRobin>()};std::cout << "round robin:\n";for (std::size_t i = 0; i < 3; ++i) { // tickets 1 to 3 (indexes 0 to 2) show(tickets[i], desk.assign(tickets[i]));}
// Change the rule while running. The old RoundRobin is destroyed here;// the tickets it assigned stay with their agents.desk.set_available("Ben", false);desk.set_rule(std::make_unique<SkillMatch>());std::cout << "Ben is offline; switching to skill match:\n";for (std::size_t i = 3; i < 6; ++i) { show(tickets[i], desk.assign(tickets[i]));}
std::cout << "open tickets:";for (const Agent& agent : desk.agents()) { std::cout << ' ' << agent.name << ' ' << agent.open_tickets;}std::cout << '\n';
// With nobody available, assign returns nullopt and changes nothing;// show() prints "waiting" for it.desk.set_available("Asha", false);desk.set_available("Chen", false);std::cout << "everyone is offline:\n";show(tickets[6], desk.assign(tickets[6]));round robin: #1 Invoice shows the wrong total -> Asha #2 Wi-Fi drops every hour -> Ben #3 Cannot log in -> ChenBen is offline; switching to skill match: #4 Refund not received -> Asha #5 VPN will not connect -> Chen #6 Printer offline -> Ashaopen tickets: Asha 3 Ben 1 Chen 2everyone is offline: #7 Password reset -> waiting: nobody availableweekend, function form: #1 Invoice shows the wrong total -> Chenleast busy, template form: #1 Invoice shows the wrong total -> Asha #2 Wi-Fi drops every hour -> Ben #3 Cannot log in -> ChenThe last two parts of the output come from the other two C++ forms, shown in the next section.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) fails, and// prints both, unless they are equal; LLD_CHECK_THROWS(expression, type)// fails unless the expression throws that type. They come from the// site's small test header, lld_test.hpp.// team() (a helper at the top of this file) gives Asha (billing), Ben// (network), and Chen (billing and network), at indexes 0, 1, and 2. The// tickets `billing`, `network`, and `any` (no skill) are defined there too.//// Each rule is tested on its own, with plain data and no desk.// Comparing with std::optional<std::size_t>{0} checks "chose index 0".// Round robin: Asha first; with Ben away the turn skips to Chen; then it// wraps back round to Asha.LLD_TEST(round_robin_takes_turns_and_skips_unavailable_agents) { std::vector<Agent> agents = team(); RoundRobin rule; LLD_CHECK(rule.choose(any, agents) == std::optional<std::size_t>{0}); agents[1].available = false; LLD_CHECK(rule.choose(any, agents) == std::optional<std::size_t>{2}); LLD_CHECK(rule.choose(any, agents) == std::optional<std::size_t>{0}); // wraps}
// All at 0 tickets: Asha, the earliest, wins the tie. With Asha 2, Ben 1,// Chen 0, Chen wins.LLD_TEST(least_busy_prefers_fewest_tickets_then_the_earliest_agent) { std::vector<Agent> agents = team(); LeastBusy rule; LLD_CHECK(rule.choose(any, agents) == std::optional<std::size_t>{0}); agents[0].open_tickets = 2; agents[1].open_tickets = 1; LLD_CHECK(rule.choose(any, agents) == std::optional<std::size_t>{2});}
// Billing: Asha (1 ticket) and Chen (0) have the skill, so Chen. Network// with Ben and Chen away: nobody skilled is free, so anyone: Asha.LLD_TEST(skill_match_falls_back_to_anyone_when_no_skilled_agent_is_free) { std::vector<Agent> agents = team(); SkillMatch rule; agents[0].open_tickets = 1; LLD_CHECK(rule.choose(billing, agents) == std::optional<std::size_t>{2}); // Chen agents[1].available = false; agents[2].available = false; LLD_CHECK(rule.choose(network, agents) == std::optional<std::size_t>{0}); // Asha}
// The desk is tested with real rules and with a broken one.// Round robin gives the first ticket to Asha. After the switch to least// busy, Ben (0 tickets, earlier than Chen) gets the next, and Asha keeps hers.LLD_TEST(changing_the_rule_keeps_existing_assignments) { HelpDesk desk{team(), std::make_unique<RoundRobin>()}; LLD_CHECK(desk.assign(any) == std::optional<std::string>{"Asha"}); desk.set_rule(std::make_unique<LeastBusy>()); LLD_CHECK(desk.assign(any) == std::optional<std::string>{"Ben"}); LLD_CHECK_EQ(desk.agents()[0].open_tickets, 1); LLD_CHECK_EQ(desk.agents()[1].open_tickets, 1);}
// Everyone offline: assign returns an empty optional instead of throwing.LLD_TEST(a_ticket_waits_when_nobody_is_available) { HelpDesk desk{team(), std::make_unique<LeastBusy>()}; for (const char* name : {"Asha", "Ben", "Chen"}) { desk.set_available(name, false); } LLD_CHECK(!desk.assign(any).has_value());}
// No rule at all, an index past the end (99 with 3 agents), and an// unavailable agent are all refused, as are resolving for an agent with// no tickets and for a name nobody has.LLD_TEST(the_desk_refuses_a_rule_that_breaks_the_contract) { // nullptr becomes an empty std::unique_ptr<AssignmentRule>. LLD_CHECK_THROWS(HelpDesk(team(), nullptr), std::invalid_argument); HelpDesk desk{team(), std::make_unique<ChoosesIndex>(99)}; LLD_CHECK_THROWS(desk.assign(any), std::logic_error); desk.set_rule(std::make_unique<ChoosesIndex>(1)); desk.set_available("Ben", false); LLD_CHECK_THROWS(desk.assign(any), std::logic_error); // Ben is unavailable LLD_CHECK_THROWS(desk.set_rule(nullptr), std::invalid_argument); LLD_CHECK_THROWS(desk.resolve("Asha"), std::logic_error); // no open tickets LLD_CHECK_THROWS(desk.resolve("Dana"), std::out_of_range);}
// The interface, std::function, and template forms, and the old switch,// all with round robin, must name the same agent for each of four tickets// (with this team that is Asha, Ben, Chen, then Asha again).LLD_TEST(all_three_forms_and_the_old_switch_agree) { HelpDesk with_interface{team(), std::make_unique<RoundRobin>()}; fn::HelpDesk with_function{team(), fn::round_robin()}; tmpl::HelpDesk<RoundRobin> with_template{team()}; before::HelpDesk with_switch{team(), before::Rule::round_robin}; for (const Ticket& ticket : {billing, network, any, billing}) { const std::optional<std::string> expected = with_interface.assign(ticket); LLD_CHECK(with_function.assign(ticket) == expected); LLD_CHECK(with_template.assign(ticket) == expected); LLD_CHECK(with_switch.assign(ticket) == expected); } LLD_CHECK_THROWS(fn::HelpDesk(team(), nullptr), std::invalid_argument);}
// LeastBusy and SkillMatch against the matching switch branches, over six// tickets, so that the counts grow and the ties change along the way.LLD_TEST(the_new_rule_classes_match_the_old_switch_branches) { HelpDesk least{team(), std::make_unique<LeastBusy>()}; before::HelpDesk least_switch{team(), before::Rule::least_busy}; HelpDesk skill{team(), std::make_unique<SkillMatch>()}; before::HelpDesk skill_switch{team(), before::Rule::skill_match}; for (const Ticket& ticket : {billing, network, any, billing, network, network}) { LLD_CHECK(least.assign(ticket) == least_switch.assign(ticket)); LLD_CHECK(skill.assign(ticket) == skill_switch.assign(ticket)); }}The first three tests check each rule with plain data and no desk,
which the switch version could not do. The next three check the
desk’s own job, including a deliberately broken rule to prove the desk
refuses a bad choice. The broken rule is a few lines in the test file:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A broken rule, to check that the desk refuses its choice.// It ignores the ticket and the agents (so their parameters have no names)// and always returns the index it was built with, even one that is out of// range or names an unavailable agent.class ChoosesIndex final : public AssignmentRule {public: explicit ChoosesIndex(std::size_t index) : index_{index} {} std::optional<std::size_t> choose(const Ticket&, std::span<const Agent>) override { return index_; }
private: std::size_t index_;};The last two tests compare the designs. One runs the same tickets
through all three forms and the old switch with round robin; the
other runs the new LeastBusy and SkillMatch classes against the
switch’s matching branches. Both agree on every ticket, so for these
inputs the redesign changed the structure without changing an
assignment.
Three ways to write a strategy in C++
Section titled “Three ways to write a strategy in C++”The interface is one way to write a strategy. C++ gives you two more, and each fits different forces.
A std::function
Section titled “A std::function”When a strategy is one function call, it can be any callable:
a lambda, a function, or an object with operator().
std::function holds whichever one it is given.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The strategy as a callable: anything that can be called with a ticket// and the agents, and returns a choice.// std::function<R(A, B)> can hold any callable taking (A, B) and returning// R: a lambda, a plain function, or an object with operator(). It owns a// copy of what it holds. A default-made std::function is empty.using ChooseAgent = std::function<std::optional<std::size_t>(const Ticket&, std::span<const Agent>)>;
// Factory functions: each returns a new callable for one rule.ChooseAgent round_robin(); // the lambda keeps its own turn counterChooseAgent least_busy_rule();
// The same desk, with the rule stored as a std::function instead of a// pointer to an interface.class HelpDesk final {public: // Throws std::invalid_argument if choose is empty. HelpDesk(std::vector<Agent> agents, ChooseAgent choose);
std::optional<std::string> assign(const Ticket& ticket); void set_rule(ChooseAgent choose); // throws std::invalid_argument if empty
private: std::vector<Agent> agents_; ChooseAgent choose_; // never empty};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Returns a lambda with its own turn counter. Three pieces of lambda syntax:// - `[next = std::size_t{0}]` creates a variable `next`, starting at 0,// that lives inside the lambda object and is kept between calls.// - `mutable` lets the lambda's body change `next` (by default it cannot// change what it captured).// - `-> std::optional<std::size_t>` states the return type. Without it, the// two returns below (a std::size_t and std::nullopt) would not agree.// The body is the same round-robin loop as RoundRobin::choose.ChooseAgent round_robin() { return [next = std::size_t{0}](const Ticket&, std::span<const Agent> agents) mutable -> std::optional<std::size_t> { for (std::size_t step = 0; step < agents.size(); ++step) { const std::size_t i = (next + step) % agents.size(); if (agents[i].available) { next = (i + 1) % agents.size(); return i; } } return std::nullopt; };}
// A lambda that captures nothing and just calls the shared helper. Its// return type is deduced from least_busy: std::optional<std::size_t>.ChooseAgent least_busy_rule() { return [](const Ticket&, std::span<const Agent> agents) { return least_busy(agents); };}
// checked() (earlier in this file, not shown) throws std::invalid_argument// if `choose` is empty, so choose_ never is.HelpDesk::HelpDesk(std::vector<Agent> agents, ChooseAgent choose) : agents_{std::move(agents)}, choose_{checked(std::move(choose))} {}
// choose_(...) calls whatever callable the std::function holds.std::optional<std::string> HelpDesk::assign(const Ticket& ticket) { return record_assignment(agents_, choose_(ticket, agents_));}The round-robin lambda keeps its turn in a captured variable, next,
and is marked mutable so that calling it can change that variable.
The real strength of this form is a rule written where it is used,
with no class to declare:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A one-off rule for the weekend, written where it is used.// The lambda is the second constructor argument. It is stored inside// the desk's std::function. It picks Chen if Chen is available, and// otherwise nobody. The explicit `-> std::optional<std::size_t>` is// needed because it returns both an index and std::nullopt.fn::HelpDesk weekend{team(), [](const Ticket&, std::span<const Agent> agents) -> std::optional<std::size_t> { for (std::size_t i = 0; i < agents.size(); ++i) { if (agents[i].name == "Chen" && agents[i].available) { return i; // Chen is on call } } return std::nullopt; }};std::cout << "weekend, function form:\n";show(tickets[0], weekend.assign(tickets[0]));Two things to know about std::function:
- It copies.
std::functionrequires a copyable callable and copies it when it is copied. A copy of the round-robin function has its ownnext, so two desks given copies take turns independently, and a copy made mid-morning starts from the turn it was copied at. Usually that is what you want. The state is shared only if the lambda captures it by reference, by pointer, or through astd::shared_ptr. - An empty
std::functionthrowsstd::bad_function_callwhen it is called, so the desk refuses an empty one up front, just as the interface form refuses a null pointer.
A template parameter
Section titled “A template parameter”When the rule is fixed for the whole program (one desk that is always least busy, or a test that always uses one rule), the choice can be made when the program is compiled:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The strategy as a type chosen when the program is compiled.// A concept is a named yes/no test on a type. AssignmentPolicy<Rule> is// true if, given a Rule called rule, a ticket, and a span of agents, the// call rule.choose(ticket, agents) compiles and returns exactly a// std::optional<std::size_t>. The `requires(...)` parameters are only// names for writing the test; nothing is created or called.template <typename Rule>concept AssignmentPolicy = requires(Rule& rule, const Ticket& ticket, std::span<const Agent> agents) { { rule.choose(ticket, agents) } -> std::same_as<std::optional<std::size_t>>; };
// The desk is a class template: Rule is filled in when it is used, as in// HelpDesk<LeastBusy>. `template <AssignmentPolicy Rule>` only accepts a// type that passes the test above; any other type is refused when the// program is compiled. No base class is needed.template <AssignmentPolicy Rule>class HelpDesk final {public: // `Rule rule = Rule{}`: if no rule is passed, a default-made one is used. explicit HelpDesk(std::vector<Agent> agents, Rule rule = Rule{}) : agents_{std::move(agents)}, rule_{std::move(rule)} {}
// rule_ is an object, not a pointer, so the compiler knows exactly which // choose() this is, and can call it directly. std::optional<std::string> assign(const Ticket& ticket) { return record_assignment(agents_, rule_.choose(ticket, agents_)); }
private: std::vector<Agent> agents_; Rule rule_; // held by value: no pointer, no null, no virtual call needed};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The rule is part of the type: this desk is always least busy. The// rule argument is left out, so a default-made LeastBusy is used.tmpl::HelpDesk<LeastBusy> simple{team()};std::cout << "least busy, template form:\n";for (std::size_t i = 0; i < 3; ++i) { show(tickets[i], simple.assign(tickets[i]));}The concept AssignmentPolicy states what a rule must provide. Any type
with a matching choose qualifies; it does not need to derive from
anything. The same RoundRobin and LeastBusy classes work here
because they happen to have that function. The standard library uses
this form all the time: the comparison you pass to std::sort, or the
Compare parameter of std::map, is a strategy chosen at compile time.
How to choose
Section titled “How to choose”| Question | Virtual interface | std::function |
Template parameter |
|---|---|---|---|
| Chosen when? | while running | while running | when compiling |
| Can the desk switch rules (FR-3)? | yes | yes | no: HelpDesk<LeastBusy> is a different type from HelpDesk<RoundRobin> |
| More than one function per strategy? | yes, naturally | awkward: one call per std::function |
yes |
| A one-off rule written in place? | needs a class | yes: a lambda | yes, but the desk’s type changes |
| Where the rule’s state lives | members of the rule object | variables captured by the lambda | members of the rule, held by value |
| Run-time cost per call | a virtual call | an indirect call; may allocate when created | none extra; the call can be inlined |
| Code size and build time | one desk | one desk | one copy of the desk per rule type, all in headers |
Rules of thumb:
- Use the virtual interface when strategies are classes with state or with more than one function, or when they are added by other modules or teams. It is the most explicit form, and the one this page uses for the main design.
- Use
std::functionwhen the strategy is one call and callers should be able to pass a lambda: callbacks, small rules, tests. - Use a template parameter when the choice never changes while the program runs and the call is in a loop hot enough to matter, which you should measure, not assume.
When to use Strategy, and when not to
Section titled “When to use Strategy, and when not to”Use it when:
- one job has several ways of being done, and the choice is made outside the code that needs it (by a setting, a user, a team lead);
- some ways of doing the job have state of their own;
- each way should be testable alone, or written by someone who cannot edit the context;
- new ways are expected, and adding one should not mean editing tested
code. (Changing the choice while running is easy with a Strategy, but
an
enumcan do that too, so on its own it is not a reason.)
Do not use it when:
- there is one way of doing the job today, “in case” there are more later. That is speculative generality; see the cost of unnecessary abstraction;
- there are a few fixed, stateless variants that one team owns. A
switchover an enumeration, or one function with a parameter, is simpler and the compiler checks it; - the variants differ only in data, such as a rate or a threshold. Pass the number; do not make a class per number.
- what changes is the object’s own stage in a lifecycle (pending, paid, shipped), and the object moves itself from one stage to the next. That is the State pattern: in Strategy, the client picks the algorithm, and the algorithm does not replace itself.
Costs and alternatives
Section titled “Costs and alternatives”| Approach | Good for | Costs |
|---|---|---|
switch on an enumeration |
few fixed, stateless variants owned by one team | every new variant edits the context; per-variant state leaks into the context |
| A parameter (a number, a flag) | variants that differ only in data | none, until the variants differ in logic |
| Strategy, virtual interface | variants with state, added by others, switched at run time | one interface and one class per variant; an owner to decide; a virtual call |
Strategy, std::function |
one-call variants, lambdas, callbacks | copies its callable; may allocate; only one call per object |
| Strategy, template parameter | a choice fixed at compile time; hot loops | cannot switch at run time; code in headers; longer builds |
Common misuse
Section titled “Common misuse”- Passing the whole context to the strategy. If
choosetook aHelpDesk&, every rule could call every desk function, includingassign. Pass only what the rule needs, as read-only data. - Letting the strategy do the context’s job. If each rule updated the counts itself, FR-5 would be implemented once per rule. Keep the invariant in the context.
- A strategy interface that grows a function for each new rule. If
skill match needed
set_skill_table()and round robin neededreset(), every rule would carry functions it does not use. Give the data to the constructor of the rule that needs it; keep the interface to the one job (interface segregation). - Moving the
switchinstead of removing it. Some code must still turn a setting such as"skill-match"into aSkillMatchobject. That is fine once, at the point where the program is wired together. It is a problem only if the sameswitchappears again wherever a rule is needed. - One strategy object shared by contexts that each assume it is theirs. A stateful rule shared between two desks mixes their state, as described under ownership.
When a requirement changes
Section titled “When a requirement changes”“Premium customers go to the agent who handled their last ticket.”
Ticket gains a customer field. A new ReturningAgent rule keeps a
std::map from customer to agent name as its own state, and falls back
to least busy. The interface does not change, because it already
receives the whole ticket. The desk does not change at all. One
caution: choose runs before the desk checks and records the
choice, so if the desk refuses it, the rule has remembered an
assignment that never happened. The rule must therefore treat its map
as a hint (fall back when the remembered agent is unavailable), not as
the truth. One open question goes to the team lead: should the rule
remember customers after it is replaced?
“Never give anyone more than five open tickets, whatever the rule.”
This is not a new way of choosing; it is a limit on every way. Put
it in the desk, next to the check in record_assignment, or wrap any
rule in a CappedRule. The wrapper holds the wrapped rule as a
std::unique_ptr<AssignmentRule>. Because a rule returns an index
into the list it is given, the wrapper cannot simply remove the agents
at the limit: that would shift the indexes. It must copy the list and
mark those agents unavailable, then pass the copy on, which costs a copy
on every call. The desk is the simpler home for this limit; the wrapper
is a preview of the Decorator pattern, and shows that a wrapper must
respect the interface’s contract exactly.
“Assignment must be the same on every server in the cluster.” Round robin’s turn now has to be shared between processes. That is no longer a low-level design question about one class; it belongs to the system’s architecture, and the rule would read the turn from a shared store.
Exercise
Section titled “Exercise”Exercise: Add a strategy and pick a form
- The billing team wants a “specialists first” rule: give the ticket to an available agent whose only skill is the ticket’s skill; if there is none, use skill match. Sketch the class. Does it need state? Does anything else change?
- For each situation, choose the virtual interface,
std::function, or a template parameter, and say why:- A command-line tool that replays last month’s tickets through least busy to produce a report. The rule never changes.
- A test that needs a rule which always picks agent 2.
- A plug-in system where another company ships rules in a library that is loaded by the desk.
- A colleague suggests making
AssignmentRule::choosetakeHelpDesk&“so rules can do anything”. What would you say?
Show the explained answer
1.
class SpecialistsFirst final
implements AssignmentRule
Data members
SkillMatch fallback_;owned by value; SkillMatch has no state
Member functions
std::optional<std::size_t> choose(const Ticket& ticket, std::span<const Agent> agents) override;
choose looks for the least busy available agent whose skills list
has exactly one entry, equal to ticket.skill; if there is none, it returns
fallback_.choose(ticket, agents). It has no state of its own. Nothing
else changes: not the interface, not the desk, not the other rules.
Only the code that turns a team’s setting into a rule object learns the
new name.
2.
- First ask whether you need a strategy at all: the tool always uses
least busy, and
LeastBusyhas no state, so calling theleast_busyhelper directly is simplest. If the tool should accept any rule, a template parameter fits: the rule is fixed for the whole run, and replaying a month of tickets is the kind of loop where avoiding an indirect call could matter. Honestly, the interface would also be fine; measure before choosing for speed. std::function, with a lambda written in the test:[](const Ticket&, std::span<const Agent>) { return std::optional<std::size_t>{2}; }. A test-only class would also work; the lambda is shorter and sits next to the check that uses it.- The virtual interface. The rules are compiled separately by someone else and chosen while the program runs, so the choice cannot be made at compile time. Rules from another company may also need state and more than one function later. (Loading libraries at run time has its own problems, such as matching compiler versions; they are beyond this page.)
3. Passing the desk gives every rule access to everything the desk
can do, including assign and set_rule, so a rule could break FR-5 or
replace itself. It also makes every rule depend on HelpDesk, so the
rules can no longer be tested with plain data. Ask what the rule needs
to read, and pass that. Here, it is the ticket and the agents.
Related patterns
Section titled “Related patterns”- State: the same shape (an object holding one of several interchangeable objects), but the held object represents the context’s current stage, and the stages switch from one to another themselves. See State, and Strategy vs State vs Template Method, which solves one problem with all three.
- Template Method: varies steps of an algorithm through inheritance from a base class that fixes the order of the steps; Strategy varies the whole algorithm through composition. See Template Method.
- Decorator: wraps an object to add behaviour while keeping its
interface, as
CappedRulewould. - Factory Method: a common way to turn a setting into the right concrete strategy. See Factory Method.
Summary
Section titled “Summary”- Strategy puts each way of doing one job behind one interface, so the context can be given any of them and can switch at run time.
- Sort data and functions first: state used by one variant belongs to that variant; invariants that every variant must respect belong to the context.
- A strategy chooses or computes; the context acts. Pass it read-only data, not the context.
- The context usually owns its strategy through
std::unique_ptr; replacing the strategy destroys its state. - In C++, choose between a virtual interface (stateful,
multi-function, run-time),
std::function(one call, lambdas), and a template parameter (fixed at compile time). - A
switchover a few fixed, stateless variants is often the better design. Use Strategy when the forces are present, not because the pattern exists.