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

Commuting is a part of our daily lives. Every day, when we leave our house for work, we have to choose transportation. As commuters, we have a lot of options - taxi, bus, or train - it really depends on our mood and the situation we are in. Like if you were in a hurry because you woke up late, then you will probably take a taxi. On another day, when you want a no-fuss seat and you have time to spare, then a bus is a good choice. On days when we want to make sure we get to a certain location on time without the hassle of getting stuck in traffic, we would take a train.

This is a perfect sample of the Strategy Pattern.

A bus, a train, and a taxi are all modes of transportation but they of course vary in many ways. They are different from one another in terms of cost, and they take different routes to get you to your destination. They are the same because they are all ways for you to get to your destination, although in varying length of travel time. They all belong to one family, which is transportation.

Let us first create a Transportation interface:

Create a Bus class that implement Transportation interface:

Create a Train class that implement Transportation interface:

Create a Taxi class that implement Transportation interface:

Lastly, we need to create a Passenger class, that represents us:

Let us see, how Passenger uses different transportations in a context:

Bus, Train and Taxi classes vary independently from Passenger class, because they all implement Transportation interface.

In our example, by applying the Strategy Pattern, we defined a family (Transportation family) of algorithms (Bus, Train and Taxi), encapsulates each one (Passenger class is only aware ofTransportation interface), and makes them interchangeable (They implement common interface). Strategy lets the algorithm vary independently from clients (Passenger class) that use it.

The end

Hopefully this simple tutorial helped you with your development.
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.