Behavioral Policy

Strategy

Strategy packages a group of interchangeable algorithms into their own classes and lets the object using them switch between algorithms at runtime through a shared interface.

Complexity
Popularity

Problem

Imagine you're building a navigation app. Depending on how the traveler gets around - on foot or by car - the route between two points has to be calculated differently: a walking route favors footpaths and shortcuts, while a road route must follow streets and traffic rules.

You could implement all these options with a giant `if/else` block inside a `Navigator` class. But every time a new travel mode is added - cycling, public transit - you have to modify that class, violating the Open/Closed Principle and making it harder to maintain.

As the number of travel modes grows, the class becomes bloated with unrelated routing logic that is difficult to test in isolation.

Solution

The Strategy pattern suggests extracting all these algorithms (route calculations) into separate classes called strategies. The original class, called the context, stores a reference to one of the strategy objects and delegates the work to it.

The context is not responsible for selecting the appropriate algorithm - the client does that. The context works with all strategies through a generic interface exposing a single method that triggers the algorithm.

This makes the context independent of concrete strategies, so you can add new travel modes without ever touching the `Navigator` class.

When to Use

  • Reach for Strategy when an object needs to pick between several variants of a behavior and that choice may change while the program runs.
  • It also helps when several classes are nearly identical except for one piece of behavior - that piece becomes the strategy, and the classes collapse into one.
  • Use it to keep an algorithm's implementation details out of a class whose main job is unrelated business logic.

Real-World Examples

  • **Payment gateways** - checkout can switch between Stripe, PayPal, or Apple Pay without changing the cart logic.
  • **`Array.prototype.sort()`** - the comparator function you pass is a strategy that defines how elements are ordered.
  • **File compression** - archiving tools let users choose between ZIP, GZIP, or BZIP2 without changing the archiving UI.