Command

Encapsulate a callback function (and necessary parameters) in an object, which allows for unlimited lifetime scope, storing, queueing, playback, and undoing of commands/actions.

Use when:

Example C++ Code

 // The abstract command class
class Command
{
public:
    virtual ~Command();
    virtual void Execute() = 0;
private:
    Command();
};

// Command to open a document issued when a button is pressed by the user
class OpenCommand : public Command
{
    OpenCommand(Application* a) {
        _application = a;
    }
    // the Document class is the Receiver, where open() is the receiver Action
    virtual void Execute() {
        const char* name = AskUser();
        Document* doc = new Document(name);
        _application->Add(document);
        document->open();
    }
protected:
    virtual const char* AskUser();
private:
    Application* _application;
};

// A generic client creation and call of a command might be like:
MyClass* reciever = new MyClass;
Command* aCommand = new SimpleCommand<MyClass>(receiver, &MyClass::Action);
aCommand->Execute(); // calls MyClass::Action()