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


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

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

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

//Set Balanced Strategy...

//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

//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 Mar 9 by:


markdown guide