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

Hi,

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.

Thanks
milani_lucieAsked:
Who is Participating?
 
jimmycdinataCommented:
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()
car.run()

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()
    {
        this.motor.run()
    }

    method changeMotor(motor)
    {
        this.motor=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.
0
 
TommySzalapskiCommented:
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.
0
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.