> For the complete documentation index, see [llms.txt](https://anon-coders-notes.gitbook.io/techwriterdev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://anon-coders-notes.gitbook.io/techwriterdev/softwareengineering/designpatterns/notes/05_behavioral/strategy.md).

# Strategy (aka Policy)

## Intent

* Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently of the clients that use it.

## Problems

* How can a class be configured with an algorithm at run-time instead of implementing an algorithm directly?
* How can an algorithm be selected and exchanged at run-time?

## Solutions

* Encapsulate an algorithm in a separate Strategy object.
* A class delegates an algorithm to a Strategy object instead of implementing an algorithm directly.

## Advantages

✅ You can swap algorithms used inside an object at runtime. ✅ You can isolate the implementation details of an algorithm from the code that uses it. ✅ You can replace inheritance with composition. ✅ Open/Closed Principle: You can introduce new strategies without having to change the context.

## Disadvantages

❌ If you only have a couple of algorithms and they rarely change, there’s no real reason to overcomplicate the program with new classes and interfaces that come along with the pattern. ❌ Clients must be aware of the differences between strategies to be able to select a proper one. ❌ A lot of modern programming languages have functional type support that lets you implement different versions of an algorithm inside a set of anonymous functions. Then you could use these functions exactly as you’d have used the strategy objects, but without bloating your code with extra classes and interfaces
