Proficient in Java Design Patterns From the first sight of the command design pattern of love (15)

1. Concept

    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.

2. Scene

    2.1: This mode is used in the workflow Activit framework. It has a total of 7 interfaces. Each interface has specific commands to execute the tables in the database. Because the activit framework will automatically generate 23 tables, these commands will be in the These tables are directly added, deleted, modified, and searched, and we just call these commands directly in the background.

 

3. Simple code implementation

    

public interface Order {

    void execute();
}
public class Apple {

    private String name = "ABC";
    private int quantity = 10;

    public void buy(){
        System.out.println("买家name="+name+" quantity="+quantity);
    }
    public void sell(){
        System.out.println("卖家name="+name+" quantity="+quantity);
    }
}
public class BuyApple implements Order {

    private Apple apple;

    public BuyApple(Apple apple) {
        this.apple = apple;
    }

    @Override
    public void execute() {
        apple.buy();
    }
}
public class SellApple implements Order {

    private Apple apple;

    public SellApple(Apple apple){
        this.apple = apple;
    }

    @Override
    public void execute() {
        apple.sell();
    }
}
public class Command {

    private List<Order> orderList = new ArrayList<>();

    public void takeOrder(Order order){
        orderList.add(order);
    }

    public void placeOrders(){
        for (Order order : orderList) {
            order.execute();
        }
        orderList.clear();
    }
}

main function execution result

public class Main {
    public static void main(String[] args) {
        Apple apple = new Apple();

        BuyApple buyStockOrder = new BuyApple(apple);
        SellApple sellStockOrder = new SellApple(apple);

        Command command = new Command();
        command.takeOrder(buyStockOrder);
        command.takeOrder (sellStockOrder);

        command.placeOrders();
    }
}

    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325572393&siteId=291194637