DEV Community

Cover image for Behavioural Patterns: Strategy Pattern
EliteSalad
EliteSalad

Posted on

Behavioural Patterns: Strategy Pattern

Strategy pattern defines a family of algorithms Defines each one of them and makes them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.

Inheritance is a pretty basic object-oriented technique that allows subclasses created from already existing classes to use functions and variables from their parent class. This easily allows behaviors to be similar and means code can be reused. There are however circumstances where an inheritance will in fact create more duplicate code than can easily be managed to bring with it all the folly of having copy-paste code from one section to another. This can occur because when inherited functions can be inherited down easily but they cannot be inherited across. Here is an example of when code would be duplicated under inheritance.

Image description

In the above UML 2 subclasses are using the same Fight function and two are also utilizing the same Eat function. Despite that, on implementation, those repeat functions will have to be written out in full twice or even more if another class shares that functionality. There is no way for the one function to be used by one of its sister classes, but strategy patterns can circumnavigate this dilemma.

Image description

A strategy pattern takes functionality away from the function within the class instead of requiring an interface class for that function to be created which can then act as a directory to select a class for them. Now that the interface class exists it can assign completely different classes even ones unrelated to the base class with the exact same functionality if required. This is the logic applied to the first UML diagram

Image description

It is possible to take this one step further completely foregoing inheritance itself and instead establishing all parts of the base class as interfaces. This would then mean the subclass would instead be a collection of the correct interfaces instead of one that inherited the correct functionality and had overridden other parts.

Image description

This complete lack of inheritance means no class in this model 'is a' form of another class and instead it is a group of classes that 'has a' bunch of other classes creating a spider web of links as opposed to a tree of inheritance. This method probably shouldn't be the default with simple projects or small use cases but it definitely has earned the right o be as prolific as inheritance in my opinion. Sandi Metz argues the benefits of composition over inheritance in her Nothing is something talk on the null object pattern.

Discussion (0)