Used in task schedulers, RTOS command queues, button handling, and automation systems.
- Decouples sender and receiver
- Enables queuing and logging
C Example
#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
#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);
}