TL;DR

“Essentially, the strategy pattern allows us to change the behavior of an algorithm at runtime.” (taken from Baeldung) .-

#### Use cases

For simple understandment, when you have a math problem, this have just one correct answer (or not jeje), but there is a lot of different ways to achieve this result. So, you could code different implementations to resolve the problem, and the strategy pattern allows you to easily change between the implementations.

You could use this pattern in different problems, for example:

  • Implement different ways to call a backend
  • Change between different algorhitms for compression

A picture is worth a thousand words (stoled obvs)

UML From wikimedia: alt text

#### How it looks in code

in github :p

An interface:

class FindStrategy {
    find(collection, predicate) { throw new Error("this is so abstract!")}
}

And possible different implementations:

class FindWithLodash extends FindStrategy{
    find (collection, predicate) {
        return _.find(collection, predicate);
    }
}
class FindWithVanilla extends FindStrategy{
    find (collection, predicate) {
        return collection.find(predicate);
    }
}

Select the strategy:

const selectedStrategy = process.env.FINDSTRATEGY || 'FindWithLodash';
const finder = new strategiesToFind[selectedStrategy]

const result = finder.find(users, predicate);

#### Keep reading!

  • https://en.wikipedia.org/wiki/Strategy_pattern
  • https://www.baeldung.com/java-strategy-pattern
  • https://dzone.com/articles/design-patterns-strategy