Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 57 ยท Behavioral Patterns

Strategy

Learn the Strategy design pattern: make algorithms interchangeable, replace long if-else chains, and use plain functions as strategies in sorting and pricing.

The Strategy pattern takes a family of algorithms, puts each one behind the same small interface, and lets a client choose which one to use. The object that uses the algorithm (the context) does not contain the algorithm itself. It just holds a strategy and asks it to do the work.

You recognize the need when you see a method full of if (mode === "a") ... else if (mode === "b") ...: shipping cost by carrier, a discount by customer type, a route by transport mode, a sort by field. Every new case means editing that method, the risk of breaking old cases grows, and the class mixes "what is being done" with "how, in each of the ways". Strategy pulls each branch into its own unit.

Three parts

Context The object that needs a job done.
Strategy The shared interface, such as price(amount).
Concrete strategies One implementation per algorithm.

The context holds a strategy and delegates to it.

1 / 2

Before: a conditional that keeps growing

Here is a shipping calculator with the conditional. Look at what adding a new carrier requires.

JS The if-else version

Press Run (or Ctrl + Enter) to see the console output here.

No output.

To add a drone carrier, you must edit shippingCost, which is shared by every other carrier. That is the situation the Open/Closed principle warns about (see Open/Closed Principle).

After: strategies

Each carrier becomes an object with a cost(weightKg) method. The context (Order) takes a strategy and asks it for the price. In JavaScript the interface is "an object with a cost method"; in Java or C++ you would declare an interface or abstract class, shown read-only below.

Java
// Read-only: the same structure in Java.
interface ShippingStrategy {
    double cost(double weightKg);
}

class StandardShipping implements ShippingStrategy {
    public double cost(double weightKg) { return 5 + weightKg * 1.0; }
}

class Order {
    private ShippingStrategy shipping;
    Order(ShippingStrategy shipping) { this.shipping = shipping; }
    void setShipping(ShippingStrategy shipping) { this.shipping = shipping; }
    double shippingCost(double weightKg) { return shipping.cost(weightKg); }
}
classDiagram
    class Order {
        -shipping
        +setShipping(s)
        +shippingCost(kg)
    }
    class ShippingStrategy {
        <<interface>>
        +cost(kg)
    }
    class Standard
    class Express
    class Pickup
    Order o--> ShippingStrategy
    ShippingStrategy <|.. Standard
    ShippingStrategy <|.. Express
    ShippingStrategy <|.. Pickup

The order depends only on the interface, so adding a carrier means adding a class and touching nothing else.

JS Shipping strategies on an order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The switch moved from a hard-coded branch to a method call. The decision about which strategy to use is still made somewhere (usually where the order is created or from user choice, often with a lookup table or a Factory Method), but it is now in one small place, and the algorithms stay independent.

Functions as strategies

When a strategy has a single method, a whole class is often more ceremony than needed. In languages with first-class functions (JavaScript, Python, Kotlin, Java lambdas, C++ std::function), the strategy can just be a function. The comparator you pass to a sort call is exactly this: array.sort(compareFn) is the Strategy pattern, with the sort as the context.

JS Sorting and pricing with function strategies

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Function strategies are lighter than classes, but classes still win when a strategy needs its own state (a rate limiter holding counters), several related methods (price and describe), or a name you want in stack traces and documentation. Use whichever matches the size of the problem.

Strategy compared with its neighbors

  • State looks identical in a diagram: a context delegates to an object. The difference is who changes it. With Strategy the client usually picks the algorithm, and strategies do not know about one another. With State, the states themselves trigger transitions and know their successors.
  • Template Method varies steps of an algorithm by inheritance (decided at compile time, per subclass). Strategy varies the whole algorithm by composition (decided at run time). See Template Method.
  • Bridge also uses composition for two hierarchies; see Bridge.
  • Command wraps a request as an object; a strategy wraps a way of computing.

When not to use it

Do not introduce Strategy for an if with two stable branches that will never change. Three is a reasonable point to ask whether the cases are likely to grow. Also note the costs: clients must know the differences among strategies to choose one, and for many tiny strategies the number of classes (or table entries) can exceed the size of the code they replace. Passing data between context and strategy can also get awkward: either pass what the strategy needs as parameters (as weightKg above) or give the strategy a reference to the context, which couples them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the Strategy pattern let you do?

    Strategy encapsulates each algorithm behind a common interface so the context can switch between them without being edited.
  2. 2. Which code smell most strongly suggests using Strategy?

    A conditional that must be edited for every new variant is the classic place to move each branch into its own strategy.
  3. 3. In JavaScript, what is the comparator passed to array.sort() an example of?

    The sort routine is the context, and the comparator is an interchangeable strategy that decides the ordering.
  4. 4. How do Strategy and State differ?

    The structures are alike. The difference is intent and who drives the change: the client for Strategy, the states themselves for State.
  5. 5. When might a class-based strategy be better than a plain function?

    Stateful or multi-method strategies fit naturally in a class, while stateless one-method strategies are usually simpler as functions.

Summary

  • Strategy puts each algorithm in its own unit behind a common interface; the context delegates to the chosen one.
  • It removes growing conditionals and follows the Open/Closed Principle: new behavior is added, not edited in.
  • In languages with first-class functions, a strategy can be a plain function, as with sort comparators and lookup tables.
  • Strategy is chosen by the client; State changes itself; Template Method varies steps by inheritance.
  • Skip it for stable two-way branches, and keep the interface small so strategies stay easy to write.

Next lesson: Observer.