Skip to content

Strategy Pattern

The strategy pattern abstracts the implementation details for how an operation is done.

The implementation of the Command Pattern can be very similar to that of the Strategy Pattern, but the purpose is not the same:

  • A command represents what is done.

  • A strategy represents how something is done.

  • Classically implemented via inheritance.

  • Better to use std::function than a base class Command and using inheritance. std::function uses Value Semantics.

std::accumulate relies on the Strategy Pattern to allow the user to specify how to combine the elements inside a container:

// Strategy: defines HOW to combine elements
const auto multiply = [](int a, int b) { return a * b; };
const auto add = [](int a, int b) { return a + b; };
std::vector<int> numbers = {1, 2, 3, 4};
auto product = std::accumulate(numbers.begin(), numbers.end(), 1, multiply);
auto sum = std::accumulate(numbers.begin(), numbers.end(), 0, add);
  • Usually executed immediately to vary algorithm behavior
  • Focus on interchangeable algorithms