DEV Community

Cover image for Strategy Pattern
Francesco Ciulla
Francesco Ciulla

Posted on • Updated on

Strategy Pattern

Strategy Pattern

Algorithm Encapsulation

GitHub Link:

Behavioral Design Pattern


The Strategy pattern, also called policy pattern, enables selecting an algorithm at runtime.
Deferring the decision about which algorithm to use, allows more flexibility and reusability


When we want to change the behavior of our application at runtime

For example, change the behavior to:

  • aggressive
  • defensive
  • balanced


  • Define different algorithms
  • Make them interchangeable at runtime, with a setStrategy() method

🔧 Apply when

  • Classes only change in behavior
  • We want Different variants of an algorithm


  • Algorithm families use inheritance for common parts Avoid conditional statements using this pattern Clients can choose the required behavior


  • Increased number of objects
  • Strategies are shared between objects

🏆 Great for

  • Encapsulate an algorithm
  • Change algorithm at runtime


//Concrete Strategy A
class AggressiveStrategy {
    constructor() { = move => "Next aggressive move";

//Concrete Strategy B
class BalancedStrategy {
    constructor() { = move => "Next balanced move";

//Concrete Strategy C
class DefensiveStrategy {
    constructor() { = move => "Next defensive move";

class AIGameStrategy {
    constructor() {
        this.setStrategy = (game) => = game; = move =>;

// --- MAIN ---

//Strategies initialization
const aggressive = new AggressiveStrategy();
const balanced = new BalancedStrategy();
const defensive = new DefensiveStrategy();

//Implement Strategy Pattern
const AI = new AIGameStrategy();

//Set Defensive Strategy

//Perform defensive action
console.log(; //Next defensive move

//Set Balanced Strategy...

//Perform balanced actions
console.log(; //Next balanced move
console.log(; //Next balanced move
console.log(; //Next balanced move

//Change Strategy to Aggressive

//Perform aggressive actions
console.log(; //Next aggressive move
console.log(; //Next aggressive move
Enter fullscreen mode Exit fullscreen mode

GitHub Link:

Top comments (0)