This is the 15th day of my participation in the August Text Challenge.More challenges in August
Command pattern is a data-driven design pattern, which belongs to behavior pattern. The request is wrapped in the object as 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.
introduce
describe | parsing |
---|---|
intentions | Encapsulate a request into an object so that customers can be parameterized with different requests. |
Mainly to solve | In a software system, the behavior requester and the behavior implementers are usually tightly coupled, but in some situations, such as the need to record, undo or redo the behavior, transaction, etc., such a tightly coupled design that cannot resist changes is not appropriate. |
When to use | In some cases, such as “record, undo/redo, transaction” processing of behaviors, the “behavior requester” and “behavior implementor” need to be decoupled. Loose coupling is achieved by abstracting a set of behaviors as objects. |
How to solve | Execute commands through caller to call receiver in order: caller → command → receiver. |
The key code | Define three roles: 1. Received real command execution object; 2. 3. Invoker uses the entry of the command object. |
Examples of application | There is only one Action core controller ActionServlet in Struts 1, which is equivalent to Invoker, while classes in the model layer will have different model classes with different applications, which is equivalent to specific commands. |
advantages | 1. The coupling degree of the system is reduced. 2. New commands can be easily added to the system. |
disadvantages | Using command mode can cause some systems to have too many specific command classes. |
Usage scenarios | Command mode can be used wherever it is considered a command, for example: 1. Each button in the GUI is a command. 2. Simulate CMD. |
Matters needing attention | The system needs to support Undo and Redo operations. You can also consider using command mode |
\
implementation
An example is ordering a stockbroker to buy or sell stocks
First create the interface Order as a command, then create the Stock class as a request. The entity command classes BuyStock and SellStock, which implement the Order interface, will perform the actual command processing. Create a class Broker as the call object that accepts and places orders.
Broker objects use a command pattern to determine which object executes which command based on the type of command. The CommandPatternDemo class uses the Broker class to demonstrate the command pattern.
Step 1- Create the command interface class
Create a command interface.
// Order.java
public interface Order {
void execute(a);
}
Copy the code
Step 2- Create the request class
Create a request class.
// Stock.java
public class Stock {
private String name = "ABC";
private int quantity = 10;
public void buy(a){
System.out.println("Stock [ Name: "+name+", Quantity: " + quantity +" ] bought");
}
public void sell(a){
System.out.println("Stock [ Name: "+name+", Quantity: " + quantity +" ] sold"); }}Copy the code
Step 3- Extend the command instance class
Create an entity class that implements the Order interface.
// BuyStock.java
public class BuyStock implements Order {
private Stock abcStock;
public BuyStock(Stock abcStock){
this.abcStock = abcStock;
}
public void execute(a) { abcStock.buy(); }}Copy the code
// SellStock.java
public class SellStock implements Order {
private Stock abcStock;
public SellStock(Stock abcStock){
this.abcStock = abcStock;
}
public void execute(a) { abcStock.sell(); }}Copy the code
Step 4- Create the calling class
Create a command invocation 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(a){
for(Order order : orderList) { order.execute(); } orderList.clear(); }}Copy the code
Step 5- Create the scene class
Use the Broker class to receive 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 = newBroker(); broker.takeOrder(buyStockOrder); broker.takeOrder(sellStockOrder); broker.placeOrders(); }}Copy the code
Step 6- Output the results
Execute the program and output the result:
Stock [ Name: ABC, Quantity: 10 ] bought
Stock [ Name: ABC, Quantity: 10 ] sold
Copy the code