Search⌘ K
AI Features

Strategy Pattern

Explore the strategy pattern to understand how it defines families of interchangeable algorithms that vary independently from the clients that use them. This lesson helps you apply the strategy pattern to solve code duplication issues in C++ by encapsulating behaviors such as fuel consumption calculation in cars, improving flexibility and maintainability.

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 ...