Command Pattern
Command Pattern
1 of 5
search...
Home
Behavioral Patterns
http://www.oodesign.com/command-pattern.html
Command
Main Menu
Home
Design Principles
Open Close Principle
Dependency Inversion Principle
Interface Segregation Principle
Single Responsibility Principle
Liskov's Substitution Principle
Creational Patterns
Singleton
Factory
Factory Method
Abstract Factory
Builder
Prototype
Object Pool
Behavioral Patterns
Chain of Responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
Strategy
Template Method
Visitor
Null Object
Structural Patterns
Adapter
Bridge
Composite
Decorator
Flyweight
Proxy
Design Pattern Books
Command Pattern
An object that contains a symbol, name or key that represents a list of commands, actions or keystrokes. This is the
definition of a macro, one that should be familiar to any computer user. From this idea the Command design pattern was
given birth.
The Macro represents, at some extent, a command that is built from the reunion of a set of other commands, in a given order.
Just as a macro, the Command design pattern encapsulates commands (method calls) in objects allowing us to issue requests
without knowing the requested operation or the requesting object. Command design pattern provides the options to queue
commands, undo/redo actions and other manipulations.
Intent
- encapsulate a request in an object
- allows the parameterization of clients with different requests
- allows saving the requests in a queue
Implementation
The idea and implementation of the Command design pattern is quite simple, as we will see in the diagram below, needing only few extra classes implemented.
Forum
What Design Pattern To Choose?
Design Principles and Patterns
Enterprise Patterns
Books
03/08/2016 15:24
2 of 5
http://www.oodesign.com/command-pattern.html
The client creates some orders for buying and selling stocks (ConcreteCommands). Then the orders are sent to the agent (Invoker).The agent takes the orders and place them
to the StockTrade system (Receiver). The agent keeps an internal queue with the order to be placed. Let's assume that the StockTrade system is closed each Monday, but the
agent accepts orders, and queue them to be processed later on.
public interface Order {
public abstract void execute ( );
}
// Receiver class.
class StockTrade {
public void buy() {
System.out.println("You want to buy stocks");
}
public void sell() {
System.out.println("You want to sell stocks ");
}
}
// Invoker.
class Agent {
private m_ordersQueue = new ArrayList();
public Agent() {
}
//ConcreteCommand Class.
class BuyStockOrder implements Order {
private StockTrade stock;
public BuyStockOrder ( StockTrade st) {
stock = st;
}
public void execute( ) {
stock . buy( );
}
}
//ConcreteCommand Class.
class SellStockOrder implements Order {
private StockTrade stock;
public SellStockOrder ( StockTrade st) {
stock = st;
}
public void execute( ) {
stock . sell( );
}
}
// Client
public class Client {
public static void main(String[] args) {
StockTrade stock = new StockTrade();
03/08/2016 15:24
3 of 5
http://www.oodesign.com/command-pattern.html
In this case the actors in the scenario are the following: The Client is the customer. He sends his request to the receiver through the waiter, who is the Invoker. The waiter
encapsulates the command (the order in this case) by writing it on the check and then places it, creating the ConcreteCommand object which is the command itself. The
Receiver will be the cook that, after completing work on all the orders that were sent to him before the command in question, starts work on it. Another noticeable aspect of the
example is the fact that the pad for the orders does not support only orders from the menu, so it can support commands to cook many different items.
Just the same way we can consider the example of an auto-repair shop. People come in with different cars that have different problems. The person at the front desk takes
their information and places the car in a queue for repair. The information on the order is encapsulated in the paper the car owner will use when he comes back to pick up the
fixed car. At some point the car will become the first item in the queue and the mechanic will repair it. Just as in the example above, the Client is the customer. The Invoker is
the person at the front desk that takes the information on the car and its problems, the ConcreteCommand is the request for fixing the car and the Receiver is the mechanic.
The most used implementation of the command pattern is the one used to implement the undo options in applications:
03/08/2016 15:24
4 of 5
http://www.oodesign.com/command-pattern.html
Let's consider a calculator application. The application represents the Client. The calculator (Receiver) class is the main class used in the application to perform the commands.
This might be as well the document class if we have a text editor application and we want to implement operations like copy/paste/etc.... When the application has to perform a
command it creates the command and sent it to the invoker. The invoker calls the execute method of the command and adds it to a list containing all the commands. The
execute method of the command delegate the call to the Calculator object. When undo operations are performed the invoker uses the list with all executed commands and calls
for each one the unexecuted method. The redo operation works in the same manner.
03/08/2016 15:24
5 of 5
http://www.oodesign.com/command-pattern.html
Instead of using one thread in which the receiver is running more threads can be created for this. But for performance issues (thread creation is consuming) the number of
threads should be limited. In this case the invoker will use a pool of receiver threads to run command asynchronously.
Hot spot
The main advantage of the command design pattern is that it decouples the object that invokes the operation from the one that know how to perform it. And this advantage
must be kept. There are implementations of this design pattern in which the invoker is aware of the concrete commands classes. This is wrong making the implementation
more tightly coupled. The invoker should be aware only about the abstract command class.
< Prev
Next >
[ Back ]
03/08/2016 15:24