Search⌘ K
AI Features

Strategy Pattern

Explore the Strategy Pattern in C++ to understand how it encapsulates algorithms, allowing them to vary independently from the clients using them. Learn to apply this pattern to avoid code duplication and enhance flexibility in software design, especially for scenarios like differing fuel consumption calculations in vehicle classes.

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 class 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 SportsCar are using fossil fuel and calculate the fuel consumption
...