Command Pattern

Command Pattern is behavioral data driven design pattern. A request is wrapped under an object as command and passed to invoker object. Invoker object looks for the appropriate object which can handle this command and passes the command to the corresponding object that executes the command.

In upcoming example an interface Order acts as a command. Stock class acts as a request. Concrete command classes BuyStock and SellStock implement Order interface and perform actual command processing. Class Broker acts as an invoker object. It can take and place orders. Broker object uses Command pattern to identify which object will execute which command based on the type of command.

Command Pattern UML Diagram

Step 1 : Create a command interface

public interface Order {
void execute();
}

Step 2 : Create a request class

public class Stock {
private String name = "ABC";
private int quanity = 10;

public void buy() {
System.out.println("Stock [ Name: " + name
+ ", Quantity: " + quanity + " ] bought");
}

public void sell() {
System.out.println("Stock [ Name: " + name
+ ", Quantity: " + quanity + " ] sold");
}
}

Step 3 : Create concrete classes implementing the Order interface

public class BuyStock implements Order {
private Stock abcStock;

public BuyStock(Stock abcStock) {
this.abcStock = abcStock;
}

@Override
public void execute() {
abcStock.buy();
}
}

public class SellStock implements Order {
private Stock abcStock;

public SellStock(Stock abcStock) {
this.abcStock = abcStock;
}

@Override
public void execute() {
abcStock.sell();
}
}

Step 4 : Create Command invoker class

public class Broker {
private List<Order> orderList = new ArrayList<>();

public void takeOrder(Order order) {
orderList.add(order);
}

public void placeOrders() {
for (Order order : orderList) {
order.execute();
}

orderList.clear();
}
}

Step 5 : Use the Broker class to take and execute commands

public class CommandPatternDemo {
public static void main(String[] args) {
Stock abcStock = new Stock();

BuyStock buyStockOrder = new BuyStock(abcStock);
SellStock sellStockOrder = new SellStock(abcStock);

Broker broker = new Broker();
broker.takeOrder(buyStockOrder);
broker.takeOrder(sellStockOrder);

broker.placeOrders();
}
}

The output will be :

Stock [ Name: ABC, Quantity: 10 ] bought
Stock [ Name: ABC, Quantity: 10 ] sold

Leave a Reply

Your email address will not be published. Required fields are marked *