Strategy Pattern

Learn about the strategy pattern in detail.

Before moving on to discuss the strategy pattern, let’s discuss why we might need to use the strategy pattern in the first place.

Example

Suppose we have a class with the name Car, and we inherit the two classes Sportscar and Sedan.

In the illustration above, we can see that the car method has three functions:

  • milesDriven(): In our example, we assume it will remain the same for all types of cars.
  • getPrice(): This will be different for each car and will be implemented by the SportsCar and Sedan classes to calculate their prices.
  • getFuelConsumption(): We can assume that both Sedan and SportCar are using fossil fuel and calculate the fuel consumption accordingly. Hence, they can inherit this function.

So far, so good. Let’s assume we have added three ...