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 Commandand using inheritance. std::function uses Value Semantics.
Example in STL
Section titled “Example in STL”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 elementsconst 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);Characteristics of Strategies
Section titled “Characteristics of Strategies”- Usually executed immediately to vary algorithm behavior
- Focus on interchangeable algorithms
Guidelines
Section titled “Guidelines”- Prefer callables over inheritance for simple behavioral patterns
- Use Strategy pattern when algorithm choice varies at runtime
Resources
Section titled “Resources”- C++ Software Design: Guideline 19: Use Strategy to Isolate How Things Are Done
- Design Patterns by Erich Gamma et al.