Command mode of Java design pattern

Posted May 28, 20202 min read

1 Introduction

The command mode in design mode is a behavioral design mode. The command mode separates the responsibility for issuing commands from the responsibility for executing commands and delegates them to different objects for execution. Typical "Everyone does their own thing to get things done."

2 . Command mode

The basic UML class diagram of the command mode is as follows:

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

  • Command An abstract interface for concrete commands.
  • ConcreteCommand is its specific implementation, you can have multiple implementations of the Command interface. The specific command itself does not implement specific business commands, but delegates the call to a business logic object to execute.
  • Receiver as the ultimate receiver of specific commands. Almost any object can be a receiver, and the details of the command are implemented by the Receiver.
  • Invoker carries commands to execute action requests. It is not responsible for creating command objects, it usually obtains pre-generated commands from the client through the constructor.
  • Client initiates specific commands to Invoker to execute.

The command mode completely decouples the initiator of the command Client and the specific executor of the command Receiver, the two parties do not directly communicate with each other, and the scalability is stronger. In addition, the command mode dynamically encapsulates the execution logic(specific Command implementation) to achieve flexible business invocation, and even multiple commands can be combined into a composite command.

We have to eat every day. The next restaurant is inevitable. If you go to the small restaurant, there is no waiter. You need to tell the chef what you want to eat. The chef is often busy. You have to run over and tell him that the chef is done. You have to put down other jobs and send them to you personally. Is the experience on both sides very bad?

After this bad dining experience, you found a big restaurant the second time. The doorman will greet you to sit down and give you a menu to check. After you choose, you will hand it to the waiter. The waiter is responsible for handing over to the chef. In the middle you want to drink a little wine, just call the waiter, she will go to the bar and get it for you. This dining experience is much better, you don't need to communicate with the chef and the bar throughout the journey. This experience is much better.

4 . Summary

The command mode is very common. Our common circuit breaker component Hystrix and Java thread pool ThreadPoolExecutor in multithreading all use the command mode, so it is necessary to learn. DEMO in simulated command mode can be obtained in the corresponding article on my personal website.

Follow the public account:Felordcn for more information

Personal blog: