The Strategy Design Pattern

Design Pattern series — part 1

Bruno Silva
The Startup

--

What is the Strategy Pattern?:

The strategy pattern is a behavioral design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.

The strategy pattern can be defined by three characteristics. You have something identified as the ‘context’. The context is a class that simply has a reference to a strategy and invokes it. An ‘IStrategy’ is an interface that defines how to work with a given strategy. Then we have a particular strategy which is a concrete implementation of that particular algorithm. This of course sounds fairly simple and honestly, the strategy design pattern is one of the easiest strategies to understand and is one of those patterns that is commonly applied in applications, so much so you might not have known you’ve just implemented a strategy. If we translate our strategy pattern into what we can find in our application:

The context could be the class that simply invokes an operation to get the total fare of transport:

--

--