Design Patterns
  • Introduction
  • Proto-Pattern
  • Anti-pattern
  • OO Design Principles
  • Classification
  • Creational Design Patterns
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Prototype
  • Structural design patterns
    • Adapter
    • Bridge
    • Composite
    • Decorator
    • Facade
    • Flyweight
    • Proxy
  • Behavioural Design Pattern
    • Chain of Responsibility
    • Command
    • Interpreter
    • Iterator
    • Mediator
    • Memento
    • Observer
    • State
    • Strategy
    • Template Method
    • Visitor
  • Concurrency Design Pattern
  • Architectural Design Pattern
  • Modern Desing Patterns
Powered by GitBook
On this page

Was this helpful?

  1. Behavioural Design Pattern

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

Last updated 5 years ago

Was this helpful?