Strategy Design Pattern - What it is ? Why it is needed ? - C#


Can you please explain to me in simple words:

What is Strategy Design Pattern ?
Why it is needed ?

Please do NOT provide me links / articles.

Who is Participating?
Let's explain it the easy way :

You have a class Car() with a method run() so you use it this way in a pseudo language :

mycar = new Car()

Now, you may want to change the run() behavior on the fly, while the program is executing. E.G : to simulate a motor failure or the use of a "boost" button in a video game.

There are several ways to do that : using conditional statements and a flag variable is one of them. The strategy pattern is another, that delegate the behaviour of the run() method to a subclass :

Class Car()
    this.motor = new Motor(this)

    // passing "this" is important for the motor so it knows what it is running

    method run()

    method changeMotor(motor)


If you want to change the car behavior, you can just change the motor (easier in a program that in the real life, right ;-) ?)

It's very useful if you have a lot of complex states : you can change and maintain them much more easily.
A strategy design pattern is a design pattern where it is not known ahead of time what algorithms will need to be run on whatever data may be coming into the system.
All the algorithms that may need to be used are compiled into the program and then the characteristics of the data or the users choices determine which algorithm should run.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.