Design Patterns - SPLessons

Command Pattern

Chapter 19

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Command Pattern

Command Pattern

shape Description

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”.

shape Advantages

  • Objects can be added easily.
  • Class remains unchanged.
  • Objects with parameters can be used.

shape Conceptual
figure

shape Examples

Crate an interface Book and import java.util package

import java.util.*;
public interface Book
{
void execute();
}

Creating a class Store.

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");
}
}

Creating a class BuyStock and implementing the interface Book.

public class BuyStock implements Book
{
private Stock abcStock;
public BuyStock(Stock abcStock)
{
this.abcStock = abcStock;
}
public void execute()
{
abcStock.buy();
}
}

Creating a class SellStock and implementing the interface Book.

public class SellStock implements Book
{
private Stock abcStock;
public SellStock(Stock abcStock)
{
this.abcStock = abcStock;
}
public void execute()
{
abcStock.sell();
}
}

Creating a class Broker.

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();
}
}

Creating a main class CommandPattern.

 
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();
}
}

shape Output

The result will be as follows.

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

Summary

shape Key Points

  • Loose coupling can be done easily.
  • Command Pattern are mostly used in request response models.