Introduction

Command design pattern is a Behavioral Patterns. This pattern encapsulates commands (method calls) in objects allowing us to issue requests without knowing the requested operation or the requesting object. Command design pattern provides the options to queue commands, undo/redo actions and other manipulations. Command design decouples the object that invokes the operation from the one that knows how to perform it. To achieve this separation, the designer creates an abstract base class that maps a receiver (an object) with an action (a pointer to a member function). The base class contains an execute() method that simply calls the action on the receiver.

Implementation

Command declares an interface for executing an operation. ConcreteCommand extends the Command interface, implementing the execute method by invoking the corresponding operations on Receiver. Clientcreates a ConcreteCommand object and sets its receiver. Invoker asks the command to carry out the request.

Example

The client creates some orders for buying and selling stocks (ConcreteCommands). Then the orders are sent to the agent (Invoker). The agent takes the orders and place them to the StockTrade system (Receiver). The agent keeps an internal queue with the order to be placed.

public interface Order {
    public abstract void execute ( );
}

// Receiver class.
class StockTrade {
    public void buy() {
        System.out.println("Buy stocks");
    }
    public void sell() {
        System.out.println("Sell stocks ");
    }
}

// ConcreteCommand Class.
class BuyStock implements Order {
    private StockTrade stock;
    public BuyStock ( StockTrade st) {
        stock = st;
    }
    public void execute( ) {
        stock.buy( );
    }
}

// ConcreteCommand Class.
class SellStock implements Order {
    private StockTrade stock;
    public SellStock ( StockTrade st) {
        stock = st;
    }
    public void execute( ) {
        stock.sell( );
    }
}

// Invoker
class Agent {  
    void placeOrder(Order order) {
        order.execute();
    }    
}

// Client
public class Client {
    public static void main(String[] args) {
        StockTrade stock    = new StockTrade();
        BuyStock bsc        = new BuyStock (stock);
        SellStock ssc       = new SellStock (stock);
        Agent agent         = new Agent();

        agent.placeOrder(bsc); // Buy Shares
        agent.placeOrder(ssc); // Sell Shares
    }
}