DP: Command

Command encapsulates a request as an object, allowing parameterization of clients with queues, logs, and undoable operations.

Used in task schedulers, RTOS command queues, button handling, and automation systems.

  • Decouples sender and receiver
  • Enables queuing and logging

C Example

c
#include <stdio.h>

void ledOn() { printf("LED ON\n"); }
void ledOff() { printf("LED OFF\n"); }

typedef void (*Command)();

void execute(Command cmd) {
    cmd();
}

int main() {
    execute(ledOn);
    execute(ledOff);
}

C++ Example

cpp
#include <iostream>
using namespace std;

class Command {
public:
    virtual void execute() = 0;
};

class LEDOn : public Command {
public:
    void execute() override { cout << "LED ON\n"; }
};

class Remote {
public:
    void press(Command* cmd) { cmd->execute(); }
};

int main() {
    Remote r;
    LEDOn on;
    r.press(&on);
}