{"id":"6b08bd3e80884893657cca1a","slug":"strategy","title":"Strategy: interchangeable algorithms instead of an if-else ladder","summary":"The Strategy pattern through courier assignment in a pierogi place: a family of interchangeable algorithms behind one interface, swapped at runtime. Code in C#, TypeScript, Java, Go and Python.","servedLang":"en","availableLangs":["pl","en"],"topics":["strategy","solid"],"techs":["dotnet","typescript","java","go","python"],"tags":["gof","behavioral","strategy","composition","open-closed"],"level":"beginner","kind":"article","access":"public","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":13,"stats":{"views":4,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:14:06.157Z","updatedAt":"2026-11-27T13:07:15.511Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"violet","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"The Strategy design pattern with examples in C#, TypeScript, Java, Go and Python: when to use it, common mistakes, and how it differs from State and Template Method.","wordCount":2437,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Halina's pierogi place delivers orders, and a dozen lines of code decide which courier rides off with the hot potato-and-cheese pierogi. In the morning the nearest courier wins; on a Friday evening it is the least busy one. "},{"type":"text","text":"Strategy","marks":[{"type":"bold"}]},{"type":"text","text":" lets you keep each of these algorithms in its own class and swap them without touching the code that uses them."}]},{"type":"callout","attrs":{"variant":"tip","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Strategy is a "},{"type":"text","text":"family of interchangeable algorithms","marks":[{"type":"bold"}]},{"type":"text","text":" hidden behind a common interface."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The object using the algorithm (the context) "},{"type":"text","text":"does not know which variant it got","marks":[{"type":"bold"}]},{"type":"text","text":" – it only knows the interface."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A new variant is a new class (or function), not another "},{"type":"text","text":"else if","marks":[{"type":"code"}]},{"type":"text","text":" in existing code."}]}]}]}]},{"type":"stats","attrs":{"items":[{"value":"1994","label":"the GoF book is published","hint":"Gamma, Helm, Johnson, Vlissides"},{"value":"11","label":"behavioral patterns in the GoF catalog","hint":"Strategy opens this series"},{"value":"0","label":"changes in the context","hint":"when a new algorithm is added"}]}},{"type":"heading","attrs":{"level":2,"id":"the-problem-an-algorithm-welded-into-the-code"},"content":[{"type":"text","text":"The problem: an algorithm welded into the code"}]},{"type":"paragraph","content":[{"type":"text","text":"The first version of the dispatcher was simple: one "},{"type":"text","text":"mode","marks":[{"type":"code"}]},{"type":"text","text":" parameter and a few branches. A year later it looked like this:"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"assign-courier.ts"},"content":[{"type":"text","text":"function assignCourier(couriers: Courier[], mode: string, raining: boolean): Courier | undefined {\n  if (mode === 'nearest') {\n    return couriers.reduce((a, b) => (b.distanceKm < a.distanceKm ? b : a));\n  } else if (mode === 'least-busy') {\n    return [...couriers].sort((a, b) => a.activeOrders - b.activeOrders)[0];\n  } else if (mode === 'rush') {\n    // copy of 'least-busy' + \"skip couriers with 4+ orders\"\n    const free = couriers.filter((c) => c.activeOrders < 4);\n    return [...free].sort((a, b) => a.activeOrders - b.activeOrders)[0];\n  }\n  if (raining) {\n    // nobody remembers why this is here\n    return couriers.find((c) => c.vehicle === 'car');\n  }\n  throw new Error(`Unknown mode: ${mode}`);\n}"}]},{"type":"paragraph","content":[{"type":"text","text":"Every rule change means editing the same function. Branches copy pieces of each other, the weather condition dangles outside the rest of the logic, and a test for \"rush mode\" has to walk through every "},{"type":"text","text":"if","marks":[{"type":"code"}]},{"type":"text","text":". You also cannot add an algorithm from the outside – say, in a loyalty module for regular customers – without modifying this file. It is a textbook violation of the Open/Closed Principle from "},{"type":"text","text":"SOLID","marks":[{"type":"link","attrs":{"href":"/en/topics/solid"}}]},{"type":"text","text":"."}]},{"type":"heading","attrs":{"level":2,"id":"the-solution-pull-the-algorithm-behind-an-interface"},"content":[{"type":"text","text":"The solution: pull the algorithm behind an interface"}]},{"type":"paragraph","content":[{"type":"text","text":"The idea is short: "},{"type":"text","text":"every way of choosing a courier becomes a separate object","marks":[{"type":"bold"}]},{"type":"text","text":" with the same "},{"type":"text","text":"pick(order, couriers)","marks":[{"type":"code"}]},{"type":"text","text":" method. The dispatcher (the context) holds a reference to \"some strategy\" and delegates the decision to it. Who picks the concrete strategy and when – configuration, a schedule, a feature flag – is a separate concern."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"classDiagram\n  direction LR\n  class Dispatcher {\n    -strategy: AssignmentStrategy\n    +use(strategy)\n    +assign(order, couriers)\n  }\n  class AssignmentStrategy {\n    <<interface>>\n    +pick(order, couriers) Courier\n  }\n  class NearestCourier {\n    +pick(order, couriers) Courier\n  }\n  class LeastBusyCourier {\n    +pick(order, couriers) Courier\n  }\n  Dispatcher o--> AssignmentStrategy : delegates\n  AssignmentStrategy <|.. NearestCourier\n  AssignmentStrategy <|.. LeastBusyCourier","caption":"The structure of the Strategy pattern"}},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Role"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"In the example"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Responsibility"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Strategy"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"AssignmentStrategy","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the common interface of all algorithms"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Concrete strategy"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"NearestCourier","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"LeastBusyCourier","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"one variant of the algorithm, unaware of the others"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Context"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Dispatcher","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"holds a strategy and delegates work to it"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Client"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"configuration, scheduler"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"chooses a strategy and hands it to the context"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"The interesting part happens at runtime: the strategy can be swapped on the fly and the dispatcher does not even notice."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"sequenceDiagram\n  participant S as Scheduler\n  participant D as Dispatcher\n  participant N as NearestCourier\n  participant L as LeastBusyCourier\n  D->>N: pick(order 1, couriers)\n  N-->>D: Ania (1.2 km)\n  Note over S,D: Friday, 6 pm – order rush\n  S->>D: use(LeastBusyCourier)\n  D->>L: pick(order 2, couriers)\n  L-->>D: Bartek (0 active orders)","caption":"Swapping the strategy on a Friday evening"}},{"type":"heading","attrs":{"level":2,"id":"implementation-in-five-languages"},"content":[{"type":"text","text":"Implementation in five languages"}]},{"type":"paragraph","content":[{"type":"text","text":"The example is deliberately small: two strategies, a context and a short demo of swapping. Notice that in TypeScript, Go and Python a strategy can simply be a "},{"type":"text","text":"function","marks":[{"type":"bold"}]},{"type":"text","text":" – the pattern does not require classes, only a shared signature."}]},{"type":"codeGroup","attrs":{"title":"Strategy – courier assignment"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"Dispatcher.cs"},"content":[{"type":"text","text":"var couriers = new List<Courier> { new(\"Ania\", 1.2, 3), new(\"Bartek\", 2.5, 0) };\nvar dispatcher = new Dispatcher(new NearestCourier());\nConsole.WriteLine(dispatcher.Assign(new Order(1, \"Długa 5\"), couriers));  // -> Ania\ndispatcher.Use(new LeastBusyCourier());                                   // Friday rush\nConsole.WriteLine(dispatcher.Assign(new Order(2, \"Krótka 7\"), couriers)); // -> Bartek\n\npublic sealed record Courier(string Name, double DistanceKm, int ActiveOrders);\npublic sealed record Order(int Id, string Address);\n\npublic interface IAssignmentStrategy\n{\n    Courier? Pick(Order order, IReadOnlyList<Courier> couriers);\n}\n\npublic sealed class NearestCourier : IAssignmentStrategy\n{\n    public Courier? Pick(Order order, IReadOnlyList<Courier> couriers) =>\n        couriers.MinBy(c => c.DistanceKm);\n}\n\npublic sealed class LeastBusyCourier : IAssignmentStrategy\n{\n    public Courier? Pick(Order order, IReadOnlyList<Courier> couriers) =>\n        couriers.OrderBy(c => c.ActiveOrders).ThenBy(c => c.DistanceKm).FirstOrDefault();\n}\n\npublic sealed class Dispatcher(IAssignmentStrategy strategy)\n{\n    private IAssignmentStrategy _strategy = strategy;\n\n    // The algorithm can be swapped at runtime without touching Dispatcher.\n    public void Use(IAssignmentStrategy strategy) => _strategy = strategy;\n\n    public string Assign(Order order, IReadOnlyList<Courier> couriers) =>\n        _strategy.Pick(order, couriers) is { } courier\n            ? $\"Order #{order.Id} -> {courier.Name}\"\n            : $\"Order #{order.Id} waits for a free courier\";\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"dispatcher.ts"},"content":[{"type":"text","text":"interface Courier { name: string; distanceKm: number; activeOrders: number }\ninterface Order { id: number; address: string }\n\n// In TypeScript a strategy can simply be a function type.\ntype AssignmentStrategy = (order: Order, couriers: readonly Courier[]) => Courier | undefined;\n\nconst nearest: AssignmentStrategy = (_order, couriers) =>\n  couriers.reduce<Courier | undefined>((best, c) => (!best || c.distanceKm < best.distanceKm ? c : best), undefined);\n\nconst leastBusy: AssignmentStrategy = (_order, couriers) =>\n  [...couriers].sort((a, b) => a.activeOrders - b.activeOrders || a.distanceKm - b.distanceKm)[0];\n\nclass Dispatcher {\n  constructor(private strategy: AssignmentStrategy) {}\n\n  use(strategy: AssignmentStrategy): void {\n    this.strategy = strategy;\n  }\n\n  assign(order: Order, couriers: readonly Courier[]): string {\n    const courier = this.strategy(order, couriers);\n    return courier ? `Order #${order.id} -> ${courier.name}` : `Order #${order.id} waits for a free courier`;\n  }\n}\n\nconst couriers: Courier[] = [\n  { name: 'Ania', distanceKm: 1.2, activeOrders: 3 },\n  { name: 'Bartek', distanceKm: 2.5, activeOrders: 0 },\n];\nconst dispatcher = new Dispatcher(nearest);\nconsole.log(dispatcher.assign({ id: 1, address: 'Długa 5' }, couriers)); // -> Ania\ndispatcher.use(leastBusy); // Friday rush\nconsole.log(dispatcher.assign({ id: 2, address: 'Krótka 7' }, couriers)); // -> Bartek"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"Dispatcher.java"},"content":[{"type":"text","text":"import java.util.Comparator;\nimport java.util.List;\nimport java.util.Optional;\n\nrecord Courier(String name, double distanceKm, int activeOrders) {}\nrecord Order(int id, String address) {}\n\n@FunctionalInterface\ninterface AssignmentStrategy {\n    Optional<Courier> pick(Order order, List<Courier> couriers);\n}\n\nfinal class NearestCourier implements AssignmentStrategy {\n    public Optional<Courier> pick(Order order, List<Courier> couriers) {\n        return couriers.stream().min(Comparator.comparingDouble(Courier::distanceKm));\n    }\n}\n\nfinal class LeastBusyCourier implements AssignmentStrategy {\n    private static final Comparator<Courier> BY_LOAD =\n        Comparator.comparingInt(Courier::activeOrders).thenComparingDouble(Courier::distanceKm);\n\n    public Optional<Courier> pick(Order order, List<Courier> couriers) {\n        return couriers.stream().min(BY_LOAD);\n    }\n}\n\npublic class Dispatcher {\n    private AssignmentStrategy strategy;\n\n    public Dispatcher(AssignmentStrategy strategy) { this.strategy = strategy; }\n\n    public void use(AssignmentStrategy strategy) { this.strategy = strategy; }\n\n    public String assign(Order order, List<Courier> couriers) {\n        return strategy.pick(order, couriers)\n            .map(c -> \"Order #\" + order.id() + \" -> \" + c.name())\n            .orElse(\"Order #\" + order.id() + \" waits for a free courier\");\n    }\n\n    public static void main(String[] args) {\n        var couriers = List.of(new Courier(\"Ania\", 1.2, 3), new Courier(\"Bartek\", 2.5, 0));\n        var dispatcher = new Dispatcher(new NearestCourier());\n        System.out.println(dispatcher.assign(new Order(1, \"Długa 5\"), couriers));  // -> Ania\n        dispatcher.use(new LeastBusyCourier());                                    // Friday rush\n        System.out.println(dispatcher.assign(new Order(2, \"Krótka 7\"), couriers)); // -> Bartek\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"dispatcher.go"},"content":[{"type":"text","text":"package main\n\nimport (\n\t\"cmp\"\n\t\"fmt\"\n\t\"slices\"\n)\n\ntype Courier struct {\n\tName         string\n\tDistanceKm   float64\n\tActiveOrders int\n}\n\ntype Order struct{ ID int }\n\n// AssignmentStrategy picks a courier; ok is false when nobody is available.\ntype AssignmentStrategy interface {\n\tPick(o Order, couriers []Courier) (c Courier, ok bool)\n}\n\n// StrategyFunc lets plain functions act as strategies (like http.HandlerFunc).\ntype StrategyFunc func(Order, []Courier) (Courier, bool)\n\nfunc (f StrategyFunc) Pick(o Order, cs []Courier) (Courier, bool) { return f(o, cs) }\n\nfunc minBy(cs []Courier, less func(a, b Courier) int) (Courier, bool) {\n\tif len(cs) == 0 {\n\t\treturn Courier{}, false\n\t}\n\treturn slices.MinFunc(cs, less), true\n}\n\nvar Nearest = StrategyFunc(func(_ Order, cs []Courier) (Courier, bool) {\n\treturn minBy(cs, func(a, b Courier) int { return cmp.Compare(a.DistanceKm, b.DistanceKm) })\n})\n\nvar LeastBusy = StrategyFunc(func(_ Order, cs []Courier) (Courier, bool) {\n\treturn minBy(cs, func(a, b Courier) int {\n\t\treturn cmp.Or(cmp.Compare(a.ActiveOrders, b.ActiveOrders), cmp.Compare(a.DistanceKm, b.DistanceKm))\n\t})\n})\n\ntype Dispatcher struct{ Strategy AssignmentStrategy }\n\nfunc (d *Dispatcher) Assign(o Order, cs []Courier) string {\n\tif c, ok := d.Strategy.Pick(o, cs); ok {\n\t\treturn fmt.Sprintf(\"Order #%d -> %s\", o.ID, c.Name)\n\t}\n\treturn fmt.Sprintf(\"Order #%d waits for a free courier\", o.ID)\n}\n\nfunc main() {\n\tcs := []Courier{{\"Ania\", 1.2, 3}, {\"Bartek\", 2.5, 0}}\n\td := &Dispatcher{Strategy: Nearest}\n\tfmt.Println(d.Assign(Order{1}, cs)) // -> Ania\n\td.Strategy = LeastBusy             // Friday rush\n\tfmt.Println(d.Assign(Order{2}, cs)) // -> Bartek\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"dispatcher.py"},"content":[{"type":"text","text":"from dataclasses import dataclass\nfrom typing import Protocol, Sequence\n\n\n@dataclass(frozen=True)\nclass Courier:\n    name: str\n    distance_km: float\n    active_orders: int\n\n\n@dataclass(frozen=True)\nclass Order:\n    id: int\n    address: str\n\n\nclass AssignmentStrategy(Protocol):\n    def __call__(self, order: Order, couriers: Sequence[Courier]) -> Courier | None: ...\n\n\ndef nearest(order: Order, couriers: Sequence[Courier]) -> Courier | None:\n    return min(couriers, key=lambda c: c.distance_km, default=None)\n\n\ndef least_busy(order: Order, couriers: Sequence[Courier]) -> Courier | None:\n    return min(couriers, key=lambda c: (c.active_orders, c.distance_km), default=None)\n\n\nclass Dispatcher:\n    def __init__(self, strategy: AssignmentStrategy) -> None:\n        self.strategy = strategy  # swap it any time, e.g. during the Friday rush\n\n    def assign(self, order: Order, couriers: Sequence[Courier]) -> str:\n        courier = self.strategy(order, couriers)\n        if courier is None:\n            return f\"Order #{order.id} waits for a free courier\"\n        return f\"Order #{order.id} -> {courier.name}\"\n\n\ncouriers = [Courier(\"Ania\", 1.2, 3), Courier(\"Bartek\", 2.5, 0)]\ndispatcher = Dispatcher(nearest)\nprint(dispatcher.assign(Order(1, \"Długa 5\"), couriers))   # -> Ania\ndispatcher.strategy = least_busy\nprint(dispatcher.assign(Order(2, \"Krótka 7\"), couriers))  # -> Bartek"}]}]},{"type":"callout","attrs":{"variant":"info","title":"Strategy as a function"},"content":[{"type":"paragraph","content":[{"type":"text","text":"In languages with first-class functions, an interface with a single method is effectively a function type. In Go the "},{"type":"text","text":"StrategyFunc","marks":[{"type":"code"}]},{"type":"text","text":" type with a "},{"type":"text","text":"Pick","marks":[{"type":"code"}]},{"type":"text","text":" method works like "},{"type":"text","text":"http.HandlerFunc","marks":[{"type":"code"}]},{"type":"text","text":" – a plain function satisfies the interface. A class makes sense when the strategy has configuration or state (a load threshold, a counter for rotation)."}]}]},{"type":"heading","attrs":{"level":2,"id":"who-chooses-the-strategy"},"content":[{"type":"text","text":"Who chooses the strategy?"}]},{"type":"paragraph","content":[{"type":"text","text":"The pattern moves the \"how\" decision into the strategy, but the \"which one\" decision still has to be made somewhere. You will usually find it in one of three places:"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Configuration at startup","marks":[{"type":"bold"}]},{"type":"text","text":" – the DI container registers one implementation of the interface ("},{"type":"text","text":"services.AddSingleton<IAssignmentStrategy, LeastBusyCourier>()","marks":[{"type":"code"}]},{"type":"text","text":"), and a change only needs a different configuration entry."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A strategy registry","marks":[{"type":"bold"}]},{"type":"text","text":" – a "},{"type":"text","text":"name → strategy","marks":[{"type":"code"}]},{"type":"text","text":" dictionary filled at startup. Halina's admin panel shows the list of keys and the dispatcher fetches a strategy by name. A single "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":" in a factory is fine – the problem was a "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":" scattered across business logic."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A runtime rule","marks":[{"type":"bold"}]},{"type":"text","text":" – a scheduler, a feature flag or an A/B test swaps the strategy on the fly, just like in the sequence diagram above."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Stateless strategies (like both in the example) can be safely shared between threads and registered as singletons. A stateful strategy – for example round-robin rotation of couriers, which remembers the last one picked – needs some thought about concurrency, or a separate instance per context."}]},{"type":"heading","attrs":{"level":2,"id":"step-by-step"},"content":[{"type":"text","text":"Step by step"}]},{"type":"timeline","attrs":{"items":[{"date":"Step 1","title":"Find the axis of change","text":"What varies independently of the rest? Here: the courier selection rule, not the way an order is saved."},{"date":"Step 2","title":"Define the interface","text":"One method with the data every variant needs (order, couriers). Do not pass the whole context \"just in case\"."},{"date":"Step 3","title":"Move branches into classes","text":"Each if becomes a concrete strategy. Duplicated code comes to light – and usually disappears."},{"date":"Step 4","title":"Inject the strategy","text":"The context receives it through a constructor or setter. A DI container or a factory picks the variant."},{"date":"Step 5","title":"Test separately","text":"You test each strategy without the dispatcher, and the dispatcher with a fake strategy."}]}},{"type":"paragraph","content":[{"type":"text","text":"What does it look like in numbers? Below is an illustrative simulation of one Friday evening: as orders pile up, the \"nearest\" strategy overloads a few couriers, while \"least busy\" spreads the work more evenly."}]},{"type":"chart","attrs":{"type":"line","title":"Average delivery time on a Friday evening","caption":"Illustrative data – made-up values, not a measurement from a real pierogi place.","unit":"min","data":{"labels":["5 pm","6 pm","7 pm","8 pm","9 pm"],"series":[{"name":"Nearest courier","values":[24,31,42,47,33]},{"name":"Least busy","values":[27,29,32,34,30]}]}}},{"type":"heading","attrs":{"level":2,"id":"when-to-use-it-and-when-not-to"},"content":[{"type":"text","text":"When to use it and when not to"}]},{"type":"prosCons","attrs":{"pros":["a new algorithm without modifying the context (Open/Closed Principle)","each variant tested in isolation","behaviour swapped at runtime (configuration, feature flags, A/B tests)","composition over inheritance – no explosion of context subclasses"],"cons":["more types and files when there are just two simple variants","the client has to understand the differences between strategies to pick the right one","the shared interface can be a compromise: one strategy needs data the others ignore"],"prosTitle":"Pros","consTitle":"Cons"}},{"type":"callout","attrs":{"variant":"warning","title":"Common mistake"},"content":[{"type":"paragraph","content":[{"type":"text","text":"A strategy that does "},{"type":"text","text":"if (order is VipOrder)","marks":[{"type":"code"}]},{"type":"text","text":" inside, or checks the type of the context, is a sign the interface is cut wrong. Strategies are meant to be interchangeable – if the context has to know which one it received, you are back to the if-else ladder, just smeared across classes."}]}]},{"type":"pullQuote","attrs":{"text":"Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.","author":"Gamma","role":"Helm, Johnson, Vlissides","source":"Design Patterns (1994)"}},{"type":"heading","attrs":{"level":2,"id":"related-patterns"},"content":[{"type":"text","text":"Related patterns"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"State","marks":[{"type":"link","attrs":{"href":"/en/topics/state"}}]},{"type":"text","text":" has an identical class diagram but a different intent: states switch the context "},{"type":"text","text":"themselves","marks":[{"type":"bold"}]},{"type":"text","text":", while a strategy is chosen from the outside."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Template Method","marks":[{"type":"link","attrs":{"href":"/en/topics/template-method"}}]},{"type":"text","text":" varies part of an algorithm through inheritance; Strategy replaces the whole algorithm through composition."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Decorator","marks":[{"type":"link","attrs":{"href":"/en/topics/decorator"}}]},{"type":"text","text":" changes the \"skin\" of an object by adding behaviour around it; Strategy changes its \"guts\"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Factory Method","marks":[{"type":"link","attrs":{"href":"/en/topics/factory-method"}}]},{"type":"text","text":" often decides which strategy to create based on configuration."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Command","marks":[{"type":"link","attrs":{"href":"/en/topics/command"}}]},{"type":"text","text":" also wraps behaviour in an object, but it represents a "},{"type":"text","text":"request","marks":[{"type":"bold"}]},{"type":"text","text":" (what to do), not a "},{"type":"text","text":"way","marks":[{"type":"bold"}]},{"type":"text","text":" (how to do it)."}]}]}]},{"type":"linkCard","attrs":{"url":"/en/topics/state","title":"State","description":"Same shape, but state objects switch the context themselves","kind":"topic","ref":"state"}},{"type":"linkCard","attrs":{"url":"/en/topics/template-method","title":"Template Method","description":"The algorithm skeleton in a base class, the steps in subclasses","kind":"topic","ref":"template-method"}},{"type":"linkCard","attrs":{"url":"/en/topics/solid","title":"SOLID","description":"The Open/Closed Principle and Dependency Inversion in practice","kind":"topic","ref":"solid"}},{"type":"heading","attrs":{"level":2,"id":"in-practice-where-you-already-use-strategy"},"content":[{"type":"text","text":"In practice: where you already use Strategy"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Platform"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Example"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"What the strategy is"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":".NET"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"IEqualityComparer<T>","marks":[{"type":"code"}]},{"type":"text","text":" decides how keys are compared"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":".NET"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"list.Sort(IComparer<T>)","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the element comparison algorithm"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Java / Spring"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"List.sort(Comparator)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"PasswordEncoder","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"comparison, password hashing ("},{"type":"text","text":"BCryptPasswordEncoder","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Argon2PasswordEncoder","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Node.js"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Passport.js: "},{"type":"text","text":"passport.use(new LocalStrategy(...))","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the authentication method – the library literally calls them strategies"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Go"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"slices.SortFunc(s, cmp)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"sort.Slice(s, less)","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the comparison function passed to the sorting algorithm"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Python"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"sorted(items, key=...)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"json.dumps(obj, default=...)","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the key function, how unknown types are serialised"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"The pattern is so common that we often do not notice it: every function that accepts a \"comparison function\" or a \"policy\" is a Strategy in miniature."}]},{"type":"resourceRef","attrs":{"resourceId":"6b0854ad1a40d7e6c24c8ea5"}},{"type":"heading","attrs":{"level":2,"id":"test-yourself"},"content":[{"type":"text","text":"Test yourself"}]},{"type":"quiz","attrs":{"question":"The dispatcher checks if (strategy is LeastBusyCourier) and then additionally skips couriers on bikes. What is wrong?","multiple":false,"options":[{"text":"Nothing – it is a valid extension of the pattern","correct":false,"explanation":"A context that knows concrete strategy classes loses the main benefit of the pattern – interchangeability."},{"text":"The context depends on a concrete strategy; the rule belongs in a strategy or a new variant","correct":true,"explanation":"Yes. The logic belongs to the strategy (or a new one, e.g. LeastBusyByCar), and the context only knows the interface."},{"text":"Strategy should be replaced with subclasses of Dispatcher","correct":false,"explanation":"Dispatcher subclasses are a step back – the algorithm is rigidly tied to the context again."}]}},{"type":"details","content":[{"type":"detailsSummary","content":[{"type":"text","text":"Interview question: how does Strategy differ from State if the diagrams are identical?"}]},{"type":"detailsContent","content":[{"type":"paragraph","content":[{"type":"text","text":"The difference is the intent and "},{"type":"text","text":"who switches","marks":[{"type":"bold"}]},{"type":"text","text":" the object. In Strategy the client (configuration, the user) chooses the algorithm, and strategies usually do not know about each other. In State the state objects represent stages of the context's life cycle and "},{"type":"text","text":"themselves","marks":[{"type":"bold"}]},{"type":"text","text":" decide on the transition to the next state (e.g. "},{"type":"text","text":"Paid","marks":[{"type":"code"}]},{"type":"text","text":" → "},{"type":"text","text":"InKitchen","marks":[{"type":"code"}]},{"type":"text","text":"). A good answer also mentions that a strategy is usually stateless and easy to share, while a state often holds data of its stage."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"exercise"},"content":[{"type":"text","text":"Exercise"}]},{"type":"paragraph","content":[{"type":"text","text":"Implement your own family of discount strategies for a shopping cart – percentage, threshold and \"best of\" – and check it with tests:"}]},{"type":"challengeRef","attrs":{"slug":"discount-strategy"}}]},"toc":[{"id":"the-problem-an-algorithm-welded-into-the-code","text":"The problem: an algorithm welded into the code","level":2,"locked":false},{"id":"the-solution-pull-the-algorithm-behind-an-interface","text":"The solution: pull the algorithm behind an interface","level":2,"locked":false},{"id":"implementation-in-five-languages","text":"Implementation in five languages","level":2,"locked":false},{"id":"who-chooses-the-strategy","text":"Who chooses the strategy?","level":2,"locked":false},{"id":"step-by-step","text":"Step by step","level":2,"locked":false},{"id":"when-to-use-it-and-when-not-to","text":"When to use it and when not to","level":2,"locked":false},{"id":"related-patterns","text":"Related patterns","level":2,"locked":false},{"id":"in-practice-where-you-already-use-strategy","text":"In practice: where you already use Strategy","level":2,"locked":false},{"id":"test-yourself","text":"Test yourself","level":2,"locked":false},{"id":"exercise","text":"Exercise","level":2,"locked":false}],"locked":false,"paywall":null,"previewRatio":0.3,"totalBlocks":44,"visibleBlocks":44,"resources":[{"id":"6b0857a53c96f2d34d0b321a","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=v9ejT8FO-7I","embedUrl":"https://www.youtube-nocookie.com/embed/v9ejT8FO-7I","title":"Strategy Pattern – Design Patterns (ep 1)","description":"","author":"Christopher Okhravi","thumbnailUrl":"https://i.ytimg.com/vi/v9ejT8FO-7I/hqdefault.jpg","durationSec":null,"lang":"en","topics":["strategy"],"techs":["general"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:37.397Z","updatedAt":"2026-11-26T16:00:37.397Z"},{"id":"6b0857bf3c96f2d34d0b4247","type":"article","provider":"web","url":"https://refactoring.guru/pl/design-patterns/strategy","embedUrl":null,"title":"Strategia / Strategy","description":"Strategia to behawioralny wzorzec projektowy pozwalający zdefiniować rodzinę algorytmów, umieścić je w osobnych klasach i uczynić obiekty tych klas wymienialnymi.","author":"Refactoring.Guru","thumbnailUrl":"https://refactoring.guru/pl/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868","durationSec":null,"lang":"pl","topics":["strategy"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":70,"verifiedAt":"2026-11-26T11:26:14.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857c33c96f2d34d0b4666","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL16942701W","embedUrl":null,"title":"Head First design patterns","description":"","author":"Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates","thumbnailUrl":"https://covers.openlibrary.org/b/id/388950-L.jpg","durationSec":null,"lang":"en","topics":["factory-method","abstract-factory","builder","prototype","singleton","adapter","bridge","composite","decorator","facade","flyweight","proxy","chain-of-responsibility","command","iterator","mediator","memento","observer","state","strategy","template-method","visitor"],"techs":["java"],"tags":["book","design-patterns"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2004-01-01T00:00:00.000Z","popularity":62,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857c83c96f2d34d0b49f2","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=IlmOokWznyI","embedUrl":"https://www.youtube-nocookie.com/embed/IlmOokWznyI","title":"Design Patterns in Dynamic Languages | Code Walks 016","description":"Do dynamically typed languages really need design patterns? 02:43 The short version of the argument 03:04 Strategy pattern 05:25 Factory pattern GEAR USED ► MIC: RØDE SmartLav+ http://amzn.to/21nVI3o ► CAMERA: iPhone 6 http://amzn.to/1UeVCXv Original upload date: Jun 24, 2016","author":"Christopher Okhravi","thumbnailUrl":"https://i.ytimg.com/vi/IlmOokWznyI/hqdefault.jpg","durationSec":null,"lang":"en","topics":["strategy"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2016-07-16T09:26:14.000Z","popularity":59,"verifiedAt":"2026-11-26T10:57:18.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857c33c96f2d34d0b4658","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL6030812W","embedUrl":null,"title":"Design Patterns: Elements of Reusable Object-Oriented Software","description":"","author":"Erich Gamma, John Vlissides, Richard Helm, Ralph Johnson","thumbnailUrl":"https://covers.openlibrary.org/b/id/6601119-L.jpg","durationSec":null,"lang":"en","topics":["factory-method","abstract-factory","builder","prototype","singleton","adapter","bridge","composite","decorator","facade","flyweight","proxy","chain-of-responsibility","command","iterator","mediator","memento","observer","state","strategy","template-method","visitor"],"techs":["general"],"tags":["book","design-patterns"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"1995-01-01T00:00:00.000Z","popularity":71,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"}],"challenges":[{"id":"6b0857af5a2625e44ecaad0d","slug":"discount-strategy","title":"Discount strategy","summary":"Interchangeable discount algorithms in a checkout: percentage, threshold and \"best of\", swapped at runtime.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":null,"status":"published","difficulty":"medium","topics":["strategy"],"techs":["python","typescript"],"tags":["strategy","e-commerce","behavioral"],"languages":["python","typescript"],"questionCount":null,"xp":20,"stats":{"attempts":1,"solves":1,"solutions":1,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.764Z"},{"id":"6b0857af5a2625e44ecaad13","slug":"design-patterns-basics-quiz","title":"Design patterns – basics","summary":"Six questions about classic GoF patterns: groups, intent and differences.","servedLang":"en","availableLangs":["pl","en"],"kind":"quiz","category":null,"status":"published","difficulty":"easy","topics":["builder","adapter","strategy","decorator","composite","facade","observer"],"techs":["general"],"tags":["quiz","gof","basics"],"languages":[],"questionCount":6,"xp":10,"stats":{"attempts":1,"solves":1,"solutions":0,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.960Z"}],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"gof-behavioral","title":"GoF behavioral patterns","items":[{"slug":"strategy","title":"Strategy: interchangeable algorithms instead of an if-else ladder","current":true},{"slug":"observer","title":"Observer: notify everyone without knowing anyone","current":false},{"slug":"command","title":"Command: a request wrapped in an object","current":false},{"slug":"state","title":"State: an object that changes behaviour with its life stage","current":false},{"slug":"template-method","title":"Template Method: a fixed recipe, interchangeable ingredients","current":false},{"slug":"iterator","title":"Iterator: walking a collection without looking inside","current":false},{"slug":"chain-of-responsibility","title":"Chain of Responsibility: pass it on until someone takes care of it","current":false},{"slug":"mediator","title":"Mediator: components talk through a coordinator","current":false},{"slug":"memento","title":"Memento: a state snapshot without breaking encapsulation","current":false},{"slug":"visitor","title":"Visitor: new operations without changing classes","current":false}]}],"prev":null,"next":{"slug":"observer","title":"Observer: notify everyone without knowing anyone"},"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}