This article includes alist of references,related reading, orexternal links,but its sources remain unclear because it lacksinline citations. Please helpimprove this article byintroducing more precise citations.(December 2012) (Learn how and when to remove this message) |
Inobject-oriented programming, thecommand pattern is abehavioraldesign pattern in which an object is used toencapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.
Four terms always associated with the command pattern arecommand,receiver,invoker andclient. Acommand object knows aboutreceiver and invokes a method of the receiver. Values for parameters of the receiver method are stored in the command. The receiver object to execute these methods is also stored in the command object byaggregation. Thereceiver then does the work when theexecute() method incommand is called. Aninvoker object knows how to execute a command, and optionally does bookkeeping about the command execution. The invoker does not know anything about a concrete command, it knows only about the commandinterface. Invoker object(s), command objects and receiver objects are held by aclient object. Theclient decides which receiver objects it assigns to the command objects, and which commands it assigns to the invoker. The client decides which commands to execute at which points. To execute a command, it passes the command object to the invoker object.
Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the class of the method or the method parameters. Using an invoker object allows bookkeeping about command executions to be conveniently performed, as well as implementing different modes for commands, which are managed by the invoker object, without the need for the client to be aware of the existence of bookkeeping or modes.
The central ideas of this design pattern closely mirror the semantics offirst-class functions andhigher-order functions infunctional programming languages. Specifically, the invoker object is a higher-order function of which the command object is a first-class argument.
The command[1]design pattern is one of the twenty-three well-knownGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
Using the command design pattern can solve these problems:[2]
Implementing (hard-wiring) a request directly into a class is inflexible because it couples the class to a particular request at compile-time, which makes it impossible to specify a request at run-time.
Using the command design pattern describes the following solution:
This enables one to configure a class with a command object that is used to perform a request. The class is no longer coupled to a particular request and has no knowledge (is independent) of how the request is carried out.
See also the UML class and sequence diagram below.

In the aboveUMLclass diagram, theInvoker class doesn't implement a request directly.Instead,Invoker refers to theCommand interface to perform a request (command.execute()), which makes theInvoker independent of how the request is performed.TheCommand1 class implements theCommand interface by performing an action on a receiver (receiver1.action1()).
TheUMLsequence diagramshows the run-time interactions: TheInvoker object callsexecute() on aCommand1 object.Command1 callsaction1() on aReceiver1 object,which performs the request.

Action is a command object. In addition to the ability to perform the desired command, anAction may have an associated icon,keyboard shortcut,tooltip text, and so on. A toolbar button or menu item component may be completely initialized using only theAction object.This C++23 implementation is based on the pre C++98 implementation in the book.
importstd;usingstd::shared_ptr;usingstd::unique_ptr;// Abstract commandclassCommand{protected:Command()=default;public:// declares an interface for executing an operation.virtualvoidexecute()=0;virtual~Command()=default;};// Concrete commandtemplate<typenameReceiver>classSimpleCommand:publicCommand{private:Receiver*receiver;Actionaction;public:usingAction=void(Receiver::*)();// defines a binding between a Receiver object and an action.SimpleCommand(shared_ptr<Receiver>receiver,Actionaction):receiver{receiver.get()},action{action}{}SimpleCommand(constSimpleCommand&)=delete;constSimpleCommand&operator=(constSimpleCommand&)=delete;// implements execute by invoking the corresponding operation(s) on Receiver.virtualvoidexecute(){(receiver->*action)();}};// ReceiverclassMyClass{public:// knows how to perform the operations associated with carrying out a request. Any class may serve as a Receiver.voidaction(){std::println("MyClass::action called");}};intmain(intargc,char*argv[]){shared_ptr<MyClass>receiver=std::make_shared<MyClass>();// ...unique_ptr<Command>command=std::make_unique<SimpleCommand<MyClass>>(receiver,&MyClass::action);// ...command->execute();}
The program output is
MyClass::actioncalled
The first published mention of using a Command class to implement interactive systems seems to be a 1985 article by Henry Lieberman.[4] The first published description of a (multiple-level) undo-redo mechanism, using a Command class withexecute andundo methods, and a history list, appears to be the first (1988) edition ofBertrand Meyer's bookObject-oriented Software Construction,[5] section 12.2.