> For the complete documentation index, see [llms.txt](https://javascript-1.gitbook.io/design-pattern/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://javascript-1.gitbook.io/design-pattern/behavioural-design-pattern/strategy.md).

# Strategy

Encapsulates an algorithm inside a class.

* Strategy lets the algorithm vary independently from clients that use it.
* The Strategy pattern encapsulates alternative algorithms (or strategies) for a particular task.
* It allows a method to be swapped out at runtime by any other method (strategy) without the client realizing it.
* Strategy is a group of algorithms that are interchangeable.

```javascript
EX:
class OperationAdd {
   doOperation(num1, num2) {
      return num1 + num2;
   }
}

class OperationSubstract {
   doOperation(num1, num2) {
      return num1 - num2;
   }
}

class OperationMultiply {
   doOperation(num1, num2) {
      return num1 * num2;
   }
}

class Context {
   private strategy;
   constructor(Strategy strategy){
      this.strategy = strategy;
   }
   executeStrategy(int num1, int num2){
      return strategy.doOperation(num1, num2);
   }
}

function run() {
   addContext = new Context(new OperationAdd());		
   console.log("10 + 5 = " + addContext.executeStrategy(10, 5)); // 10 + 5 = 15
   substractContext = new Context(new OperationSubstract());		
   console.log("10 - 5 = " + substractContext.executeStrategy(10, 5)); // 10 - 5 = 5
   multiplyContext = new Context(new OperationMultiply());		
   console.log("10 * 5 = " + multiplyContext.executeStrategy(10, 5)); // 10 * 5 = 50
}

run();
```
