1. Introduction

The command pattern in design pattern is a behavioral design pattern. The command mode separates the responsibility of issuing and executing commands and delegates them to different objects. It’s a classic case of “everyone doing their own thing to get it done.”

2. Command mode

The basic UML class diagram for command pattern is as follows:

There are several roles in command mode. Based on the class diagram above, I will introduce them one by one:

  • Command An abstract interface for a specific Command.
  • ConcreteCommandIt’s a concrete implementation of that, and you can have more than oneCommandInterface implementation. The concrete command itself does not implement the concrete business command, but rather delegates the invocation to a business logic object to execute.
  • Receiver Indicates the final Receiver of a specific command. Almost any object can be a Receiver, and the details of commands are implemented by the Receiver.
  • InvokerCarry command executionactionThe request. It is not responsible for creating command objects; it usually gets pre-generated commands from the client through constructors.
  • The Client initiates specific commands and sends them to Invoker to execute.

In command mode, the Client, the initiator of a command, and the Receiver, the executor of a command, are completely decoupled. The two parties do not communicate with each other directly, and the expansibility is stronger. In addition, the Command mode will execute logic for dynamic parameterization encapsulation (specific Command implementation) to achieve flexible business calls, and even multiple commands can be combined into compound commands.

3. Popular explanation

Every day we have to eat, we have to go to a restaurant, if you go to a small restaurant, there is no waiter, you have to tell the chef what you want to eat, the chef is usually busy, you have to run to tell him, the chef has to put aside other work to bring you there. Both sides experience is not very bad.

After this bad dining experience, you go to a big restaurant the second time. The waiter will greet you and give you a menu to check. After you choose, give it to the waiter, the waiter is responsible for giving it to the chef, and the waiter takes it to you. If you want a drink in between, all you have to do is call the waitress, and she’ll go to the bar and get it for you. It’s a much better dining experience. You don’t have to talk to the chef or the bar. The experience is much better.

4. To summarize

Command mode is so common that it’s used in Hystrix, a common circuit breaker, and ThreadPoolExecutor, a thread pool in Java multithreading, so it’s worth learning about. A DEMO of the simulated command mode is available in the corresponding article on my website.

Follow our public id: Felordcn for more information

Personal blog: https://felord.cn