Command Pattern
The command pattern abstracts different kinds of operations.
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.
This pattern is classically implemented via inheritance.
Now it is is typically better to use std::function, rather than a base class Command and using inheritance, because using std::function enables Value Semantics.
Example in STL
Section titled “Example in STL”std::for_each relies on the Command Pattern to allow the user to specify what to do with the elements inside a container:
// Define PrintNumber commandconst auto PrintNumber = [](int number) { std::cout << number << "\n"; };
std::vector<int> numbers = {1,2,3};std::for_each(numbers.begin(), numbers.end(), PrintNumber);Guidelines
Section titled “Guidelines”- Prefer callables over inheritance for simple behavioral patterns
- Use Command pattern for operations that need to be stored or queued
Resources
Section titled “Resources”- Design Patterns by Erich Gamma et al.: Classical implementation of inheritance
- C++ Software Design: Guideline 21: Use Command to Isolate What Things Are Done