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.

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();

Last updated