Command Pattern Tutorial with Java Examples

Command mode

Command Pattern is a data-driven design pattern that is a behavioral pattern. The request is wrapped in an object in the form of a command and passed to the calling object. The calling object looks for a suitable object that can handle the command and passes the command to the corresponding object, which executes the command.


Intent: Encapsulate a request into an object so that you can parameterize the client with different requests.

Main solution: In software systems, behavior requesters and behavior implementers are usually a tightly coupled relationship, but in some cases, such as the need to record, revoke or redo the behavior When dealing with transactions, etc., this tightly coupled design that is not resistant to change is not appropriate.

When to use: In some situations, such as "recording, undoing/redoing, and transacting" behaviors, such tight couplings that are not resistant to change are not appropriate. In this case, how to decouple the "behavior requester" from the "behavior implementer"? By abstracting a set of behaviors into objects, you can achieve loose coupling between the two.

How to solve: The caller is called by the caller to execute the command, in the order: caller → recipient → command.

Key Code: defines three roles: 1. Received the actual command execution object 2. Command 3. Invoker uses the entry of the command object

Application example: The action core controller ActionServlet in struts 1 has only one, which is equivalent to Invoker, and the model layer class will have different model classes with different applications, which is equivalent to specific Command.

Advantages: 1. Reduced system coupling. 2. New commands can be easily added to the system.

Disadvantages: Using command mode may result in some systems having too many specific command classes.

Usage Scenario: Command mode can be used wherever it is a command, such as: 1. Each button in the GUI is a command. 2. Simulate CMD.

Note: The system needs to support the Undo and Redo operations of the command. You can also consider using the command mode. See the extension of the command mode.


We first create the interface Order as a command and then create the Stock class as the request. The entity command classes BuyStock and SellStock implement the Order interface and will perform the actual command processing. Create the class Broker as the calling object, which accepts the order and can place an order.


Broker object uses the command mode to determine which object executes which command based on the type of the command. CommandPatternDemo, our demo class uses the Broker class to demonstrate command mode.


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 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 an entity class that implements the Order interface.

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

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

Step 4

Create a command call class.

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

Step 6

Executing the program, outputting results:

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

javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition