# Strategy

> Define a family of interchangeable algorithms, each in its own class — swap them at runtime without changing the code that uses them.

- **Category**: Software Design
- **Subcategory**: behavioral
- **Canonical URL**: https://designpattern.fyi/patterns/strategy/

---

## Description
**Intent**: Extract varying algorithms into separate classes so they can be selected, swapped, and extended independently of the code that uses them.

**Context**: Your sorting function needs to be pluggable (quicksort vs. mergesort vs. timsort). Your navigation app needs to switch between road, walking, and cycling routes. Your payment processor needs to handle credit card, PayPal, and crypto. Hardcoding these switches creates conditional sprawl.

**Solution**: Define a Strategy interface. Implement each algorithm as a concrete Strategy class. A Context object holds a reference to the current Strategy and delegates the algorithm call. Client code sets the Strategy; the Context executes it.


## Use Cases
Use when you have multiple variants of an algorithm, need to switch between them at runtime, or want to isolate algorithm implementation from the code that invokes it.



## Implementation Example

```javascript
class NavigationStrategy {
  buildRoute(a, b) {}
}

class RoadStrategy extends NavigationStrategy {
  buildRoute(a, b) { return `Road route from ${a} to ${b}`; }
}

class WalkingStrategy extends NavigationStrategy {
  buildRoute(a, b) { return `Walking route from ${a} to ${b}`; }
}

class Navigator {
  setStrategy(strategy) { this.strategy = strategy; }
  buildRoute(a, b) { return this.strategy.buildRoute(a, b); }
}

```



## Trade-offs


### Advantages

- Swap algorithms at runtime — the Context doesn't care which one is active.

- Each algorithm is isolated and independently testable.

- New strategies plug in without touching the Context or other strategies.




### Considerations & Drawbacks

- Unnecessary complexity if you only have two algorithms that never change.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/strategy)

