The Jade Emperor's Legend of the Monkey King Going to Heaven, the Java Design Pattern of Making a Harass in Heaven: Command Mode

Example

The system needs to design a command line interface. The user can enter commands to execute a certain function. The functions of the system will continue to increase, and the commands will continue to increase.
How to add each function to this command line interface?
After the command line program is written, how can I add commands and functions flexibly without modification due to the addition of functions?
Here is an example of milk tea sold at a milk tea shop:

public class MashedTaroMilk {
    
    

    public void build() {
    
    
        System.out.println("奶茶师傅制作芋泥啵啵奶茶。。。");
    }
}
public class StrawBerryMilk {
    
    
    public void build() {
    
    
        System.out.println("奶茶师傅制作草莓奶茶。。。");
    }
}

Waiter category: Responsible for receiving customers and selling milk tea

public class Waiter {
    
    
    public void receiver(String command) {
    
    
        System.out.println("您选择了:" + command);
        switch (command) {
    
    
            case "芋泥啵啵奶茶" :
                new MashedTaroMilk().build();
                break;
            case "草莓奶茶" :
                new StrawBerryMilk().build();
                break;
            default :
                System.out.println("您点的奶茶本店没有。。。");
                break;
        }
    }

    public void showMenu() {
    
    
        System.out.println("您好,本店有以下奶茶:");
        System.out.println("\t芋泥啵啵奶茶");
        System.out.println("\t草莓奶茶");
    }
}

Test category:

public class Client {
    
    

    public static void main(String[] args) {
    
    
        waiter();
    }

    public static  void waiter() {
    
    
        Waiter waiter = new Waiter();
        waiter.showMenu();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择:");
        String chooseMilk = scanner.nextLine();
        waiter.receiver(chooseMilk);
        scanner.close();
    }
}

Insert picture description here
Now if the milk tea is increased, you need to modify the switch statement in the waiter class, but you don’t want to modify it. What should I do?

Improve the code

Define an interface for making milk tea, and all milk teas implement it:

public interface Command {
    
    
    /** 制作奶茶接口 */
    void build();
}

Implementation class:

public class AppleMilk implements Command {
    
    
    @Override
    public void build() {
    
    
        System.out.println("开始制作苹果奶茶。。。");
    }
}
public class PlainMilk implements Command {
    
    
    @Override
    public void build() {
    
    
        System.out.println("开始制作原味奶茶。。。");
    }
}

Now another waitress is hired to receive:

public class Waitress {
    
    

    private Map<String, Command> map = new HashMap<>();

    public void addMilk(String name, Command command) {
    
    
        map.put(name, command);
    }

    public void receiver(String command) {
    
    
        System.out.println("您选择了:" + command);
        Command command1 = map.get(command);
        if (command1 != null) {
    
    
            command1.build();
        } else {
    
    
            System.out.println("您点的奶茶本店没有。。。");
        }
    }

    public void showMenu() {
    
    
        System.out.println("您好,本店有以下奶茶:");
        map.keySet().forEach((item)->{
    
    
            System.out.println("\t" + item);
        });
    }
}

Test category:

public class Client {
    
    

    public static void main(String[] args) {
    
    
        waitress();
    }

    public static void waitress() {
    
    
        Waitress waitress = new Waitress();
        waitress.addMilk("苹果奶茶", new AppleMilk());
        waitress.addMilk("原味奶茶", new PlainMilk());
        waitress.showMenu();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择:");
        String chooseMilk = scanner.nextLine();
        waitress.receiver(chooseMilk);
        scanner.close();
    }
}

Insert picture description here
After the above improvements, every time a new milk tea is added, only the interface needs to be implemented.

Command mode

definition

In order to decouple the caller and the specific implementer of the function, the coupling degree of the system is reduced, and the flexibility is improved.

intention

Encapsulate a request into an object so that you can parameterize customers with different requests

Mainly solve the problem

In a software system, the behavior requester and the behavior implementer are usually in a tightly coupled relationship. However, in certain situations, such as when behaviors need to be recorded, undo or redone, transactions, etc., this type of tightness cannot resist changes. Coupled design is not suitable

When to use

In some situations, such as "recording, undo/redo, transaction" and other processing of behavior, 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 as objects can achieve loose coupling between the two

Pros and cons

advantage:

  1. Reduce the coupling degree of the system
  2. Increased flexibility

Disadvantages:
using the command mode may cause too many specific command classes in some systems

Class diagram:
Insert picture description here
roles involved:

  1. Client (Client) role: Create a concrete command (ConcreteCommand) object and determine its receiver
  2. Command (Command) role: declares an abstract interface for all specific command classes, usually implemented by interfaces or abstract classes
  3. The role of concrete command (ConcreteCommand): defines a weak coupling between the receiver and the behavior; implements the execute() method, responsible for invoking the corresponding operations of the receiver, the execute() method is usually called the execution method
  4. Invoker role: responsible for calling the command object to execute the request, the related method is called the action method
  5. Receiver (Receiver) role: responsible for the specific implementation and execution of a request, any class can become a receiver, the method of implementing and executing the request is called the action method

The corresponding classes are as follows:
Client class:

public class Client {
    
    

    public static void main(String[] args) {
    
    
        Receiver receiver = new Receiver();
        Command command = new ConcreteCommand(receiver);
        Invoker invoker = new Invoker(command);
        invoker.action();
    }
}

Command interface:

public interface Command {
    
    

    /** 执行方法 */
    void execute();
}

ConcreteComman implementation class:

public class ConcreteCommand implements Command {
    
    

    private Receiver receiver;

    public ConcreteCommand(Receiver receiver) {
    
    
        this.receiver = receiver;
    }

    @Override
    public void execute() {
    
    
        System.out.println("do something......");
        receiver.action();
    }
}

Invoker class:

public class Invoker {
    
    

    private Command command;

    public Invoker(Command command) {
    
    
        this.command = command;
    }

    /** 行动方法 */
    public void action() {
    
    
        command.execute();
    }
}

Receiver class:

public class Receiver {
    
    

    public Receiver() {
    
    

    }

    /** 行动方法 */
    public void action() {
    
    

    }
}

The Jade Emperor's Legend of the Monkey King Going to Heaven

Before the Monkey King made a big noise in the Heavenly Palace, the Jade Emperor ordered Taibai Jinxing to call the Monkey King to heaven. This decree of the Jade Emperor was an order, and Taibai Jinxing was responsible for delivering the imperial decree, and the specific executor was the Monkey King. :
Abstract interface, all imperial edicts need to implement it:

public interface ImperialEdictCommand {
    
    

    /** 抽象圣旨,具体圣旨都必须具备的接口 */
    void command();
}

The specific order is the specific imperial edict of calling the Monkey King to heaven:

public class SkyReportsConcreteCommand implements ImperialEdictCommand {
    
    

    private MonkeyKingReceiver receiver;

    public SkyReportsConcreteCommand(MonkeyKingReceiver receiver) {
    
    
        this.receiver = receiver;
    }

    @Override
    public void command() {
    
    
        System.out.println("宣美猴王孙悟空上天报道!");
        receiver.action();
    }
}

The Jade Emperor issued a decree:

public class TheJadeEmperorClient {
    
    

    public static void main(String[] args) {
    
    
        System.out.println("玉皇大帝颁布一道圣旨,宣美猴王上天报道!");
        MonkeyKingReceiver receiver = new MonkeyKingReceiver();
        ImperialEdictCommand command = new SkyReportsConcreteCommand(receiver);
        GreatWhitePlanetInvoker invoker = new GreatWhitePlanetInvoker();
        invoker.setCommand(command);
        invoker.action();
    }
}

Taibai Venus is responsible for conveying the will to the Monkey King:

public class GreatWhitePlanetInvoker {
    
    

    private ImperialEdictCommand command;

    public void setCommand(ImperialEdictCommand command) {
    
    
        this.command = command;
    }

    /** 请求者太白金星调用此方法,要求美猴王上天 */
    public void action() {
    
    
        System.out.println("太白金星传玉帝圣旨!");
        command.command();
    }
}

The specific executor is the Monkey King:

public class MonkeyKingReceiver {
    
    

    public MonkeyKingReceiver() {
    
    

    }
    public void action() {
    
    
        System.out.println("美猴王孙悟空上天,大闹天宫!");
    }
}

Insert picture description here
Class Diagram:
Insert picture description here

The difference between command mode and strategy mode

The structure of the command mode is as follows: the structure of the
Insert picture description here
strategy mode is as follows: the
Insert picture description here
strategy mode: focuses on the realization of multiple algorithms for a behavior, interchangeable algorithms, such as discounts and discounts are algorithms, you can choose one of them to buy, buy, buy

Command mode: The focus is on providing flexible execution methods for multiple actions, such as the milk tea above. Each customer's order to buy milk tea is an action, and different milk tea production methods are different, so you need to be flexible to make milk tea

Guess you like

Origin blog.csdn.net/qq_34365173/article/details/108108946