Strategy pattern

suggest change

A strategy pattern can be used in JavaScript in many cases to replace a switch statement. It is especially helpful when the number of conditions is dynamic or very large. It allows the code for each condition to be independent and separately testable.

A strategy object is simply an object with a function for each condition. A missing name can still find an inherited method such as toString, so the lookup below is not limited to the strategies written in the object. Example:

const AnimalSays = {
    dog () {
        return 'woof';
    },

    cat () {
        return 'meow';
    },

    lion () {
        return 'roar';
    },

    // ... other animals

    default () {
        return 'moo';
    }
};

The above object can be used as follows:

function makeAnimalSpeak (animal) {
    // Match the animal by type
    const speak = AnimalSays[animal] || AnimalSays.default;
    console.log(animal + ' says ' + speak());
}

Results:

makeAnimalSpeak('dog') // logs "dog says woof"
makeAnimalSpeak('cat') // logs "cat says meow"
makeAnimalSpeak('lion') // logs "lion says roar"
makeAnimalSpeak('snake') // logs "snake says moo"

In the last case, our default function handles any missing animals.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents