Command mode of design pattern

Time:2020-11-26

Command mode command

Intro

The command mode encapsulates a request into an object, so that it can be parameterized with different requests, queue or log requests, and support revocable operations.

Command mode is to encapsulate the command, the caller initiates the command request, and the receiver executes the request.

When we call, the timing of execution is first the caller class, then the command class, and finally the receiver class.
In other words, the execution of a command is divided into three steps, and its coupling degree is much lower than that of encapsulating all operations in a class,
This is the essence of the command mode: to separate the caller and the executor of the command, so that both parties do not have to care about how the other side operates.

Basic structure:

  • Command: the abstraction of the command. The class declares the command to be executed. Generally speaking, it needs to expose oneExecuteMethod is used to execute the command
  • Concretecommand: implementation class of concrete command
  • Invoker: the caller responsible for invoking the command
  • Receiver: the receiver, responsible for receiving and executing commands

Sample

Consider an example:

public class Receiver
{
    public void Action()
    {
        Console.WriteLine("Action in receiver");
    }
}

public abstract class Command
{
    protected readonly Receiver Receiver;

    protected Command(Receiver receiver) =>
        Receiver = receiver ?? throw new ArgumentNullException(nameof(receiver));

    public abstract void Execute();
}
public class ConcreteCommand : Command
{
    public ConcreteCommand(Receiver receiver) : base(receiver)
    {
    }

    public override void Execute()
    {
        Receiver.Action();
    }
}

public class Invoker
{
    private Command _command;

    public void SetCommand(Command command)
    {
        _command = command;
    }

    public void ExecuteCommand()
    {
        _command.Execute();
    }
}


var receiver = new Receiver();
var command = new ConcreteCommand(receiver);
var invoker = new Invoker();
invoker.SetCommand(command);
invoker.ExecuteCommand();

More

The command mode encapsulates the request (command) as an object, so that different requests can be used to parameterize other objects (inject different request dependencies into other objects), and it can support the queuing execution, logging, revocation and other (additional control) functions of requests (commands).

The main functions and application scenarios of command mode are to control the execution of commands, such as asynchronous, delayed, queued execution of commands, undo redo commands, store commands, log commands, etc., which is where command mode can play a unique role.

To code implementation, the core means of command mode is to encapsulate functions into objects.

Reference

  • https://github.com/WeihanLi/DesignPatterns/tree/master/BehaviorPattern/CommandPattern