Home  >  Article  >  Java  >  How to implement command pattern in Java design pattern

How to implement command pattern in Java design pattern

WBOY
WBOYforward
2023-05-10 17:52:061393browse

Personal understanding: Separate multiple commands in a class and put one command in each class to achieve decoupling. One class only corresponds to one function. When using the command, another class will uniformly manage all commands.

Disadvantages: If there are too many functions, too many classes will be created.

Command Pattern is a data-driven design pattern, which is behavioral model. 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.

Introduction

Intent: Encapsulate a request into an object, allowing you to parameterize clients with different requests.

Main solution: In software systems, the behavior requester and the behavior implementer usually have a tightly coupled relationship, but in some cases, such as the need to record, cancel or redo the behavior This kind of tightly coupled design that cannot resist changes is not suitable when doing business, transaction processing, etc.

When to use: In some situations, such as "recording, undo/redo, transaction" and other processing of actions, this kind of tight coupling that cannot resist changes is inappropriate. . In this case, how to decouple the "behavior requester" from the "behavior implementer"? Abstracting a set of behaviors into objects can achieve loose coupling between them.

How to solve: Call the receiver through the caller to execute the command, the order is: caller→command→receiver.

Key code: Separate the commands in the class to create classes for them. These command classes have the same parent class.

Advantages:

  • Reduced coupling.

  • New commands can be easily added to the system.

Disadvantages: Using command mode may cause some systems to have too many specific command classes.

Usage scenarios: Command mode can be used wherever commands are considered, for example: 1. Every button in the GUI is a command. 2. Simulate CMD.

Note: The system needs to support the undo (Undo) operation and recovery (Redo) operation of the command, and you can also consider using the command mode.

Implementation

We first create the interface Order as the command, and then create the Stock class as the request. The entity command classes BuyStock and SellStock implement the Order interface and will perform actual command processing. Create a class Broker as the calling object, which accepts orders and can place orders. The Broker object uses the command mode 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.

Specific implementation steps

1. Create a Java project.

2. Create a stock request class Stock.

package src.com.设计模式.命令模式;
/*
* 股票类
* */
public class Stock {
    private String name;
    private int quantity;
    public Stock(String name, int quantity) {
        this.name = name;
        this.quantity = quantity;
    }
    public void buy(){
        System.out.println("股票买入成功"+name+",股数:"+quantity);
    }
    public void sell(){
        System.out.println("股票卖出成功"+name+",股数: "+quantity);
    }
}

3. Create a command interface Order.

package src.com.设计模式.命令模式;
public interface Order {
    void execute();
}

4. Create the entity class BuyStock that implements the Order interface.

package src.com.设计模式.命令模式;
public class BuyStock implements Order{
    //依赖于Stock对象
    private Stock stock;
    public BuyStock(Stock stock) {
        this.stock = stock;
    }
    @Override
    public void execute() {
        //购买目标股票的业务操作
        stock.buy();
    }
}

5. Create the entity class SellStock that implements the Order interface.

package src.com.设计模式.命令模式;
public class SellStock implements Order{
    private Stock stock;

    public SellStock(Stock stock) {
        this.stock = stock;
    }
    @Override
    public void execute() {
        stock.sell();
    }
}

6. Create a command to call the class Broker.

package src.com.设计模式.命令模式;
import java.util.ArrayList;
import java.util.List;
/*
* 股票经纪人类
* */
public class Broker {
    private List<Order> orderList = new ArrayList<>();
    //1.接受订单
    public void takeOrder(Order order){
        orderList.add(order);
    }
    //2.执行订单
    public void placeOrders(){
        orderList.forEach(fun ->{
            fun.execute();
        });
    }
}

7. Create the CommandPatternDemo class, and then use the Broker class to accept and execute commands.

package src.com.设计模式.命令模式;
public class CommandPatternDemo {
    public static void main(String[] args) {
        Stock stock = new Stock("002607",100);
        BuyStock buyStock = new BuyStock(stock);
        SellStock sellStock = new SellStock(stock);
        Broker broker = new Broker();
        broker.takeOrder(buyStock);
        broker.takeOrder(sellStock);
        broker.placeOrders();
    }
}

8. Execute the program and output the results.

The above is the detailed content of How to implement command pattern in Java design pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete