Match this design pattern:
Encapsulates an algorithm inside a class
The strategy pattern is used to solve problems that might (or is foreseen they might) be implemented or solved by different strategies and that posses a clearly defined interface for such cases, being ecah strategy perfectly valid in is own with some of them being preferable on some situations allowing the application to switch between them on runtime.
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.