In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate 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.
It allows us to achieve complete decoupling between the sender and the receiver. (A sender is an object that invokes an operation, and a receiver is an object that receives the request to execute a certain operation. With decoupling, the sender has no knowledge of the Receiver's interface.) The term request here refers to the command that is to be executed. The Command pattern also allows us to vary when and how a request is fulfilled. Therefore, a Command pattern provides us flexibility as well as extensibility.
A Command Pattern says to “encapsulate a request under an object as a command and pass it to invoker object. Invoker object looks for the appropriate object which can handle this command and pass the command to the corresponding object and that object executes the command".
It is also known as Action or Transaction.
Advantage of command pattern
It separates the object that invokes the operation from the object that actually performs the operation.
It makes easy to add new commands, because existing classes remain unchanged.
Command in Java Core libraries
All implementations of java.lang.Runnable
All implementations of javax.swing.Action
Command in the Real World
1. Command pattern is executed in the real world while table order at a restaurant: the waiter takes the order, which is a command from the customer. This order is then queued for the kitchen staff. The waiter tells the chef that the new order has come in, and the chef has enough information to cook the meal.
2. When you need parameterize objects according to an action performed.
3. When you need to create and execute requests at different times.
4. When you need to support rollback, logging or transaction functionality.
UML for command pattern
These are the following participants of the Command Design pattern:
Command: This is an interface for executing an operation.
ConcreteCommand: This class extends the Command interface and implements the execute method. This class creates a binding between the action and the receiver.
Client: This class creates the ConcreteCommand class and associates it with the receiver.
Invoker: This class asks the command to carry out the request.
Receiver: This class knows to perform the operation.