Design Patterns - SPLessons
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 [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]

shape Output

The result will be as follows. [java] Store [ Name: ABC, Quantity: 10 ] bought Store [ Name: ABC, Quantity: 10 ] sold[/java]

Summary

shape Key Points

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