Skip to content

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.

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 command
const auto PrintNumber = [](int number) { std::cout << number << "\n"; };
std::vector<int> numbers = {1,2,3};
std::for_each(numbers.begin(), numbers.end(), PrintNumber);