loading...
Cover image for Strategy Pattern

Strategy Pattern

francescoxx profile image Francesco Ciulla ・2 min read

Strategy Pattern

Algorithm Encapsulation

GitHub Link: https://github.com/FrancescoXX/Design-Patterns-Strategy-Javascript


Behavioral Design Pattern

Intro

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

⚡️Recognize

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

For example, change the behavior to:

  • aggressive
  • defensive
  • balanced

💡Intent

  • 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

✅Pro

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

⚠️Cons

  • Increased number of objects
  • Strategies are shared between objects

🏆 Great for

  • Encapsulate an algorithm
  • Change algorithm at runtime

/**
 * STRATEGY PATTERN JAVASCRIPT IMPLEMENTATION
 */

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

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

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

//Strategy
class AIGameStrategy {
    constructor() {
        this.setStrategy = (game) => this.game = game;
        this.next = move => this.game.next(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
AI.setStrategy(defensive);

//Perform defensive action
console.log(AI.next()); //Next defensive move

//Set Balanced Strategy...
AI.setStrategy(balanced);

//Perform balanced actions
console.log(AI.next()); //Next balanced move
console.log(AI.next()); //Next balanced move
console.log(AI.next()); //Next balanced move

//Change Strategy to Aggressive
AI.setStrategy(aggressive);

//Perform aggressive actions
console.log(AI.next()); //Next aggressive move
console.log(AI.next()); //Next aggressive move

GitHub Link: https://github.com/FrancescoXX/Design-Patterns-Strategy-Javascript

Posted on by:

Discussion

markdown guide