Strategy Pattern


The definition of the strategy pattern is:

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

What are algorithms here?

"Identify the aspects of the application 
that vary and separate them from what stays the same."

Those aspects are the algorithms which can be encapsulated and make interchangeable, and it lets those varying aspects to vary independently from the client which uses those.

As an example lets take a Car. (Implementations of Car are the clients)

Gear system in a car is varying from car to car. It can be manually, automatically, tiptronic or some new system which may be introduced tonight.

Take what varies and encapsulate it so it won't affect the rest of our code

To avoid affecting the rest of the code, those varying aspects are taken out and encapsulate those,

public abstract class Car {

   private GearSystem gearSystem;
 
   public void setGearSystem(GearSystem gearSystemParam){
      this.gearSystem = gearSystemParam;
   }
   //Other methods
}

We encapsulate those varying GearSystems as one super type called GearSystem.

     public interface GearSystem {

	public void changeGear();

     }

This makes the Gear systems are independent from any car.

The result is : Fewer unintended consequences from code 
changes and more flexibility in your systems
StrategyPattern

Class diagram for strategy pattern

More descriptive example is on git