top of page
Writer's pictureThe Tech Platform

The Command Pattern in Java



The command pattern is a behavioral design pattern and is part of the GoF‘s formal list of design patterns. This pattern intends to encapsulate in an object all the data required for performing a given action (command)


The command pattern encapsulates a request as an object, thereby letting us parameterize other objects with different requests, queue or log requests, and support undoable operations.


In command pattern there is a Command object that encapsulates a request by binding together a set of actions on a specific receiver. It does so by exposing just one method execute() that causes some actions to be invoked on the receiver.


Parameterizing other objects with different requests in our analogy means that the button used to turn on the lights can later be used to turn on stereo or maybe open the garage door.


queue or log requests, and support undoable operations means that Command’s Execute operation can store state for reversing its effects in the Command itself. The Command may have an added unExecute operation that reverses the effects of a previous call to execute.It may also support logging changes so that they can be reapplied in case of a system crash.


Command Pattern is used:

  • When you need parameterize objects according to an action perform.

  • When you need to create and execute requests at different times.

  • When you need to support rollback, logging or transaction functionality.


Advantages:

  • Makes our code extensible as we can add new commands without changing existing code.

  • Reduces coupling the invoker and receiver of a command.


Disadvantages:

  • Increase in the number of classes for each individual command

Example:

Let's understand the example of adapter design pattern by the above UML diagram.


UML for command pattern:



These are the following participants of the Command Design pattern:

  1. Command This is an interface for executing an operation.

  2. ConcreteCommand This class extends the Command interface and implements the execute method. This class creates a binding between the action and the receiver.

  3. Client This class creates the ConcreteCommand class and associates it with the receiver.

  4. Invoker This class asks the command to carry out the request.

  5. Receiver This class knows to perform the operation.



Implementation

We have created an interface Order which is acting as a command. We have created a Stock class which acts as a request. We have concrete command classes BuyStock and SellStock implementing Order interface which will do actual command processing. A class Broker is created which 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. CommandPatternDemo, our demo class, will use Broker class to demonstrate command pattern.


Step 1

Create a command interface.

Order.java

public interface Order 
{
    void execute();
}


Step 2

Create a request class.

Stock.java

public class Stock 
{
    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");
     }
}


Step 3

Create concrete classes implementing the Order interface.


BuyStock.java

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

SellStock.java

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


Step 4

Create command invoker class.


Broker.java

import java.util.ArrayList;
import java.util.List;
   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();
  }
}


Step 5

Use the Broker class to take and execute commands.


CommandPatternDemo.java

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


Step 6

Verify the output.

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


Resource: Tutorialpoint, Javapoint, baeldung


The Tech Platform

0 comments

Recent Posts

See All

Comentarios


bottom of page