Design Pattern Download: The Strategy Pattern
The Strategy pattern is a Behavioral Pattern used in software engineering when we want to create a group of algorithms and put them in their own class as opposed to making them methods in one bloated class.
Example
Imagine we want to build a simple calculator which takes in two numbers and an operation (or strategy) to be done on those two numbers. For such a simple use case we could just create a Calculator class with methods for each of the operations, but when one “operation” requires several helper functions and 100s of lines of code, that can get messy very fast. What can we do? We can separate these strategies into their own class to reduce the clutter and keep the behaviors isolated, we can then set the calculator to use whatever strategy we want to at that the time of execution.
When to use a Strategy?
- When we want to be able to switch between different variants of an algorithm during runtime
What is the Strategy composed of?
- The Context (Calculator)
- The Strategies (the operations)
Implementation
The Context
The Strategies
Now we can do as many calculations as our hearts desire!
15
5