Design Patterns — The Strategy Pattern

Ilan Belfer
4 min readMar 19, 2021

At the beginning of my road as a developer, I found myself having a hard time to come up with good designs to my code.

As a junior developer at the time, I didn't know much about design patterns, and only after I started learning about it, I found out how much it could have made my life easier.

Easier not only by how the code looks, but it kind of forcing you to think MORE about what you need to do in the task, how to implement it, how it will be used, really think of the little things, and how much it could help those who read and use my code after me.

This article will focus on the Strategy Pattern, and hopefully there will be more to come!

The code written in PHP,
but the principles are the same.

I will try to make it as short and focused as I can.

In computer programming, the strategy pattern is a behavioral software 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.

In a nutshell, this strategy will help us select and replace different functions (behaviors) to different classes in the most modular way.

Here is an example of robots classes:

The basic robot model we built, can run at basic speed of 15 kmph,
and fill it energy using fuel.

We got 2 more robots, which can run and fill their energy as well:

The Sport robot overwrite the run behavior, because it can run faster.

The Green robot overwrite the fill resources behavior, because it uses electricity power (replacing battery).

Now, lets say we made a third robot, which can run fast as the sport robot, and use electricity power like the green robot:

The advanced robot has the behaviors of the 2 other robots:
It sharing the run behavior with the sport robot,
and sharing the fill resources behavior with the green robot.

And as you can see clearly - we have duplicated code, and it's only has 2 behaviors right now.

What if we add a NEW behavior to the basic robot, let's say -

jump() {

echo 'Jumping 1 meter';

};

And 2 of our robots jump differently from the basic robot
(let's say jumping 5 meters), and have the exact same jump method with duplicated code:

Robots as robots, are modular. What if we want to change now one of the robots to work with different power resource? or change the running speed because we add it more power?

You can see where it's going..

What we can do here? We can encapsulate the behaviors!

Now, we encapsulated each behavior to a separated class.
It gives us so much more flexibility. So How it will work now?

Now, we don't even need a separated class for each robot!
The behaviors are so modular and flexible that can create the robot just by inject the right behaviors:

I really tried to make it as understandable as I can.
Really hope you learn something from it, Thank you!

--

--