BehavioralC++verifiedVerified

Command Pattern in C++

Encapsulates a request as an object, allowing you to parameterize clients, queue or log requests, and support undoable operations.

How to Implement the Command Pattern in C++

1Step 1: Define the Command interface

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

2Step 2: Receiver

class TextEditor {
    std::string text_;
public:
    void insert(const std::string& s) { text_ += s; }
    void deleteLast(size_t n) {
        if (n <= text_.size()) text_.erase(text_.size() - n);
    }
    const std::string& getText() const { return text_; }
};

3Step 3: Concrete commands

class InsertCommand : public Command {
    TextEditor& editor_;
    std::string text_;
public:
    InsertCommand(TextEditor& ed, std::string text)
        : editor_(ed), text_(std::move(text)) {}
    void execute() override { editor_.insert(text_); }
    void undo() override { editor_.deleteLast(text_.size()); }
};

4Step 4: Invoker with undo stack

class CommandInvoker {
    std::vector<std::unique_ptr<Command>> history_;
public:
    void execute(std::unique_ptr<Command> cmd) {
        cmd->execute();
        history_.push_back(std::move(cmd));
    }

    void undo() {
        if (!history_.empty()) {
            history_.back()->undo();
            history_.pop_back();
        }
    }
};

int main() {
    TextEditor editor;
    CommandInvoker invoker;

    invoker.execute(std::make_unique<InsertCommand>(editor, "Hello"));
    invoker.execute(std::make_unique<InsertCommand>(editor, " World"));
    std::cout << editor.getText() << "\n";  // "Hello World"

    invoker.undo();
    std::cout << editor.getText() << "\n";  // "Hello"
}

Command Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Command Pattern in the Real World

Think of a restaurant order ticket. A waiter (invoker) takes your order and writes it on a slip (command). The slip is handed to the kitchen (receiver) which executes it. The waiter doesn't cook anything—they just carry and deliver orders. Tickets can be queued, cancelled before cooking, or reviewed in an audit log at day's end.