AlgorithmsCodilityPatternsTutorials

The strategy pattern (also known as policy) is one of my favorites, because it allows you to change the behavior of an object without utilizing subclassing, therefore resulting in a more decoupled code, that is easier to reason about.

You have probably seen it in use somewhere, without knowing it or not, because frequency of occurrence of this pattern is pretty high. The formal GOF definion is:
“Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.”

The application of this pattern is huge! Whenever you have a big number of similar behaviors, you should consider utilizing this pattern. For example, you are making a painting app, and every brush has pretty similar, but still different behavior. You can simply set the current brush property using a strategy pattern, and call the draw method on it. Another great example is validation. You can decouple your validation handling with the actual validation logic by simply detecting the strategy needed, and set it appropriately.

Let’s try to build a simple pub visitor, setting the strategy of i’ts movement to something you will remember 🙂

You can see how easy this was! We just defined a few behaviors, and as long as they apply to the same contract( walk and run methods), you can interchange them as you wish. Adding a new behavior now is effortless and the code is nice and clean.

If you are using Typescript or Flow, you can ensure that your strategies implement the same interface, being certain that nothing can go wrong. If not, you set a prototype on the PubVisitor constructor that throws an error if the movement methods have not been implemented on the concrete strategy.

This was the last one in this Javascript GOF patterns series, i hoped you enjoyed it and learned a lot!