Command Mode
The Command Pattern is a data-driven design pattern; it belongs to the behavioral pattern category.
The command pattern encapsulates a request as an object, allowing you to parameterize clients with different requests, queue requests or log requests, and support undoable operations.
Command pattern structure diagram:

Introduction
Intent
Encapsulate a request as an object, allowing users to parameterize clients with different requests.
Main problem solved
- Solve the tight coupling problem between requesters and executors in software systems, especially in scenarios requiring behavior recording, undo/redo, or transaction processing.
Use Cases
- When behavior recording, undo/redo, or transaction processing is needed, use the command pattern to decouple requesters and executors.
Implementation
- Define a command interface: the interface that all commands must implement.
- Create concrete commands: concrete classes implementing the command interface, containing methods to execute requests.
- Caller: holds command objects and triggers the execution of commands.
- Recipient: the object that actually executes the command.
Key code
- Receiver (Receiver): the actual object that executes the command.
- Command (Command): define the interface for executing commands.
- Invoker (Invoker): the entry point for using command objects.
Application Example
- Struts 1: ActionServlet acts as the Invoker, and classes in the model layer act as concrete Commands.
Advantages
- Reduced coupling: reduced coupling between requesters and executors.
- Easy to extend: new commands can be easily added to the system.
Disadvantages
- Too many command classes: the system may have too many concrete command classes, increasing system complexity.
Usage recommendation
- In a GUI, each button or menu item can be regarded as a command.
- Use the command pattern in scenarios that need to simulate command-line operations.
Notes
- If a system needs to support Undo and Redo operations for commands, the command pattern is a suitable choice.
structures
Mainly involves the following core roles:
-
Command (Command):
- Defines an interface for executing operations, usually containing a
executemethod, used to call the specific operation.
-
Concrete Command (ConcreteCommand):
- Implements the command interface, responsible for executing specific operations. It usually contains a reference to the receiver, and completes request processing by calling the receiver's methods.
-
Receiver:
- Knows how to perform the operations related to the request; the object that actually executes the command.
-
Invoker:
- The object that sends the command; it contains a command object and can trigger the execution of the command. The Invoker does not handle the request directly, but does so by passing the request to the command object.
-
Client (Client):
- Creates a concrete command object and sets its Receiver, then hands the command object to the Invoker for execution.
Create a class that implements
We first create the interface that acts as the command Order, then create the class that acts as the request Stock . The concrete command class BuyStock and SellStock, which implements the Order interface, will perform the actual command processing. Create the class that acts as the invoker Broker, which accepts orders and can place orders.
Broker The object uses the Command pattern to determine which object executes which command based on the type of the command.CommandPatternDemo Class uses Broker class to demonstrate the 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 that implement 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 a 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 accept 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
Run the program, output result:
Stock [ Name: ABC, Quantity: 10 ] bought
Stock [ Name: ABC, Quantity: 10 ] sold