# 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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://anon-coders-notes.gitbook.io/techwriterdev/softwareengineering/designpatterns/notes/05_behavioral/strategy.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
