Command Pattern is a behavioral pattern and a data driven pattern. In command pattern, request is sent to the invoker and invoker will send the request to the encapsulated command object. Command object sends the request to a specific receiver to perform the task. Command pattern is also known as "Action" or "Transaction".
Advantages
Objects can be added easily.
Class remains unchanged.
Objects with parameters can be used.
Conceptual
figure
Command: Command is used for declaring an interface to execute an operation.
ConcreteCommand: Concrete Command extends the Command interface and implements the Execute method for invoking the operations executed on Receiver. ConcreteCommand acts as a link between the Receiver and action.
Client : Client can create a ConcreteCommand object and set the receiver.
Invoker : Invoker will carry the command to the request.
Receiver: Receiver will perform the operations.
Examples
Crate an interface Book and import java.util package
[java]
import java.util.*;
public interface Book
{
void execute();
}[/java]
Creating a class Store.
[java]
public class Store
{
private String name = "ABC";
private int quantity = 10;
public void buy()
{
System.out.println("Stock [ Name: "+name+",
Quantity: " + quantity +" ] bought");
}
public void sell()
{
System.out.println("Stock [ Name: "+name+",
Quantity: " + quantity +" ] sold");
}
}[/java]
Creating a class BuyStock and implementing the interface Book.
[java]
public class BuyStock implements Book
{
private Stock abcStock;
public BuyStock(Stock abcStock)
{
this.abcStock = abcStock;
}
public void execute()
{
abcStock.buy();
}
}[/java]
Creating a class SellStock and implementing the interface Book.
[java]
public class SellStock implements Book
{
private Stock abcStock;
public SellStock(Stock abcStock)
{
this.abcStock = abcStock;
}
public void execute()
{
abcStock.sell();
}
}[/java]
Creating a class Broker.
[java]
public class Broker
{
private List<Order> orderList = new ArrayList<Order>();
public void takeOrder(Order order)
{
orderList.add(order);
}
public void placeOrders()
{
for (Order order : orderList)
{
order.execute();
}
orderList.clear();
}
}[/java]
Creating a main class CommandPattern.
[java]
public class CommandPattern
{
public static void main(String[] args)
{
Store abcStock = new Store();
BuyStock buyStockOrder = new BuyStock(abcStock);
SellStock sellStockOrder = new SellStock(abcStock);
Broker broker = new Broker();
broker.takeOrder(buyStockOrder);
broker.takeOrder(sellStockOrder);
broker.placeOrders();
}
}
[/java]
Output
The result will be as follows.
[java]
Store [ Name: ABC, Quantity: 10 ] bought
Store [ Name: ABC, Quantity: 10 ] sold[/java]
Summary
Key Points
Loose coupling can be done easily.
Command Pattern are mostly used in request response models.