First, the command mode(Command)
Command mode well understood, for example, the commander ordered the soldiers to do something, from the perspective of the whole matter, the role of the commander is to issue a password, the password passed through to the soldiers ' ears, soldiers to carry out. The process is good, the three mutual decoupling, no one side to rely on other people, just do their own thing, the commander wants the result, not to pay attention to how the soldiers are realized. Let's look at the diagram:
Invoker is the caller (commander), receiver is the callee (soldier), and MyCommand is the command that implements the commands interface, holds the receiving object, and looks at the implementation code:
- Public Interface Command {
- public void exe ();
- }
- Public Class mycommand implements Command {
- private receiver receiver;
- Public mycommand (receiver receiver) {
- this. receiver = receiver;
- }
- @Override
- public void exe () {
- Receiver.action ();
- }
- }
- public class RECEIVER {  
- public void action () {
- system.out.println ( "command received!"
- }
- }  
- Public class Invoker {
- private Command command;
- Public Invoker (Command command) {
- this. Command = command;
- }
- public void action () {
- Command.exe ();
- }
- }
- Public class Test {
- public static void main (string[] args) {
- Receiver receiver = new receiver ();
- Command cmd = new mycommand (receiver);
- Invoker Invoker = new Invoker (CMD);
- Invoker.action ();
- }
- }
Output: Command received!
This is very good understanding, the purpose of the command mode is to achieve the command of the issuer and the executor decoupling between the implementation of the request and execution of separation, familiar with struts should know that struts is actually a request and presentation separation technology, which inevitably involves the idea of command mode!
Reprinted from Https://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html
------Command mode for Java 23 design Patterns