This is the 16th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Today we’re going to look at the command pattern, which is a design pattern that is used infrequently, not very well understood, and only applies in certain circumstances. Therefore, for the time being, we are not ready to study in depth.

An overview of the

Command Pattern :(Command Pattern) encapsulates a request as an object, allowing you to parameterize customers with different requests, queue requests, or log requests. And support for undoable operations.

In layman’s terms, it is easier to extend by encapsulating a series of request commands without directly calling the methods of the real implementer.

When to use:

  • In some situations, such as “record, undo/redo, transaction” processing of behavior, such tight coupling that cannot resist change is not appropriate. In this case, how to decouple the “behavior requester” from the “behavior implementor”? Loose coupling can be achieved by abstracting a set of behaviors as objects.

UML class diagram:

Role Composition:

  1. Client role: Create a ConcreteCommand object and determine its receiver.

  2. Command role: Declares an abstract interface to all concrete Command classes.

  3. ConcreteCommand roles: Define a weak coupling between the receiver and the behavior; Implement the execute() method, which is responsible for invoking the recipient’s actions. The execute() method is usually called the execute method.

  4. The Invoker role: Is responsible for calling the command object to perform the request. The related methods are called action methods.

  5. Receiver role: Responsible for implementing and executing a request. Any class can be a receiver, and the methods that implement and execute requests are called action methods.

Generic code

Receiver role

public class Receiver {
    // Execute the corresponding operation of the command
    public void action(a) {
        System.out.println("Execute the operation corresponding to the command"); }}Copy the code

Abstract command role

public interface Command {
    void execute(a);
}
Copy the code

Specific Command Roles

public class ConcreteCommand implements Command {
    // Hold the corresponding receiver object
    private Receiver receiver = null;

    @Override
    public void execute(a) {
        // The corresponding method of the receiver object is usually invoked to allow the receiver to actually perform the function
        receiver.action();
    }

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

Requester role

public class Invoker {
    /** * holds the command object */
    private Command command = null;
    /** * constructor */
    public Invoker(Command command){
        this.command = command;
    }
    /** ** ** /
    public void action(a){ command.execute(); }}Copy the code

Client Role

public class Client {
    public static void main(String[] args) {
        // Create the receiver
        Receiver receiver = new Receiver();
        // Create a command object and set its receiver
        Command command = new ConcreteCommand(receiver);
        // Create requester and set the command object in it
        Invoker invoker = new Invoker(command);
        // Execute methodinvoker.action(); }}Copy the code

Results:

Execute the operations corresponding to the command

I think the example in this blog post is very good: command mode of design mode _ newbie blog _ CSDN blog _ command mode

Application scenarios

  1. Command pattern exists in Struts2 action calls

  2. The underlying implementation of transaction mechanism in database

  3. Command undo and restore: Methods to add corresponding undo and restore commands (such as transaction rollback in a database)

conclusion

Differences between command mode and policy mode:

The policy pattern consists of defining, creating, and using policies. In terms of code structure, it is very much like the factory pattern. The difference is that the strategy pattern focusing on “strategy” or the specific application scenarios, “algorithm” is used to solve according to the runtime state from a set of strategies to select different strategies, and the factory pattern encapsulated objects on the creation process, the objects have no any qualified business scenario, can be a strategy, but also can be other things. From a design point of view, these two modes are completely different.

In the policy pattern, different policies have the same purpose, different implementations, and are interchangeable with each other. For example, BubbleSort and SelectionSort are both designed to sort, but one uses a BubbleSort algorithm and the other uses a SelectionSort algorithm. In command mode, different commands have different purposes, correspond to different processing logic, and cannot be replaced with each other.