In the book "Java and Patterns" of Dr. Shanhong, this is how the command mode is described:
The command pattern belongs to the behavior pattern of the object. Command mode is also known as action mode or trading (Transaction) mode.
The command pattern encapsulates a request or operation into an object. The command mode allows the system to parameterize the client using different requests, queue requests, or log request logs, which can provide undo and redo functions for the command.
structure of the command pattern
The command pattern is the encapsulation of the command. The command mode divides the responsibility for issuing the command and the responsibility for executing the command, delegating it to different objects.
Each command is an action: the requesting party makes a request to perform an action, the receiving party receives the request, and executes the action. The command pattern allows the requesting party and the receiving party to be independent, so that the requesting party does not have to know the interface of the party receiving the request, not to know how the request was received, and whether the operation was executed, when it was executed, and how it was executed.
The command allows the requesting party and the party receiving the request to evolve independently, with the following advantages:
(1) The command mode makes it easy to add new commands to the system.
(2) Allow the party receiving the request to decide whether to veto the request.
(3) It is easier to design a command queue.
(4) The revocation and recovery of the request can be easily achieved.
(5) If required, it is easier to log commands into the logs.
The following is a schematic system that describes the structure of the command pattern.
The command pattern involves five characters, each of which is:
Client Role: Create a specific command (Concretecommand) object and determine its recipient.
command role: declares an abstract interface to all specific command classes.
specific command (concretecommand) role: defines a weak coupling between a receiver and a behavior, and implements the Execute () method, which is responsible for invoking the corresponding operation of the receiver. The Execute () method is often called the execution method.
Requestor (Invoker) role: responsible for invoking the Command object execution request, the related method is called the action method.
Receiver Role: responsible for specific implementation and execution of a request. Any class can be a recipient, and the method of implementing and executing the request is called the action method.
Source
Recipient Role Class
Public class Receiver { /** * Actually executes the command corresponding to the operation */public void Action () { System.out.println ("perform operation");} }
Abstract command Role Class
Public Interface Command { /** * Execute method * /void execute ();}
Specific command role classes
Public classConcretecommandImplementsCommand {//hold the corresponding recipient object PrivateReceiver receiver =NULL; /*** Construction Method*/ PublicConcretecommand (receiver receiver) { This. Receiver =receiver; } @Override Public voidExecute () {//the corresponding method of the recipient object is usually transferred, allowing the receiver to actually perform the functionreceiver.action (); }}
Requestor role Class
Public classInvoker {/*** Hold Command object*/ PrivateCommand command =NULL; /*** Construction Method*/ PublicInvoker (Command command) { This. Command =command; } /*** Methods of action*/ Public voidaction () {Command.Execute (); }}
Client Role Classes
Public classClient { Public Static voidMain (string[] args) {//Create a recipientReceiver receiver =NewReceiver (); //Create a Command object, set its recipientCommand command =NewConcretecommand (receiver); //Create the requestor and set the Command object inInvoker Invoker =NewInvoker (command); //Execution Methodinvoker.action (); }}
Audioplayer System
Julia has a cassette recorders, the recorder has broadcast (Play), Rewind (Rewind) and stop (stop) function, the keyboard of the recorder is the requestor (Invoker) role, Julie (Julia) is the client role, and the recorder is the recipient role. The command class plays the role of abstract commands, while Playcommand, Stopcommand, and Rewindcommand are the specific commands classes. Julia does not need to know how the broadcast (play), Rewind (rewind), and stop (stop) functions are performed, and the details of these commands are all implemented by the keyboard (Keypad). Julie (Julia) just needs to press the appropriate key on the keyboard.
A tape recorder is a typical command mode. The Recorder button separates the client from the operation details of the recorder.
Source
Receiver role, played by Sound Recorder class
Public class Audioplayer { publicvoid play () { System.out.println ("Play ..."); } Public void Rewind () { System.out.println ("Rewind ..." ); Public void Stop () { System.out.println ("Stop ...");} }
Abstract command Role Class
Public Interface Command { /** * Execute method * /public void execute ();}
Specific command role classes
Public class Implements Command { private audioplayer myaudio; Public Playcommand (Audioplayer audioplayer) { = audioplayer; } /** * Execution Method * / @Override publicvoid Execute () { myaudio.play (); }}
Public class Implements Command { private audioplayer myaudio; Public Rewindcommand (Audioplayer audioplayer) { = audioplayer; } @Override publicvoid execute () { myaudio.rewind (); }}
Public class Implements Command { private audioplayer myaudio; Public Stopcommand (Audioplayer audioplayer) { = audioplayer; } @Override publicvoid execute () { myaudio.stop (); }}
Requestor role, played by keyboard class
Public classKeypad {PrivateCommand Playcommand; PrivateCommand Rewindcommand; PrivateCommand Stopcommand; Public voidSetplaycommand (Command playcommand) { This. Playcommand =Playcommand; } Public voidSetrewindcommand (Command rewindcommand) { This. Rewindcommand =Rewindcommand; } Public voidSetstopcommand (Command stopcommand) { This. Stopcommand =Stopcommand; } /*** Execute Playback method*/ Public voidPlay () {Playcommand.execute (); } /*** Perform Rewind method*/ Public voidRewind () {rewindcommand.execute (); } /*** Execute Playback method*/ Public voidStop () {stopcommand.execute (); }}
Client role, played by Julie Little girl
Public classJulia { Public Static voidMain (String[]args) {//Create a Recipient objectAudioplayer Audioplayer =NewAudioplayer (); //To Create a Command objectCommand Playcommand =NewPlaycommand (Audioplayer); Command Rewindcommand=NewRewindcommand (Audioplayer); Command Stopcommand=NewStopcommand (Audioplayer); //Create requester ObjectKeypad Keypad =NewKeypad (); Keypad.setplaycommand (Playcommand); Keypad.setrewindcommand (Rewindcommand); Keypad.setstopcommand (Stopcommand); //TestKeypad.play (); Keypad.rewind (); Keypad.stop (); Keypad.play (); Keypad.stop (); }}
The results of the operation are as follows:
Macro Command
The so-called Macro command is simply a command that contains multiple commands and is a combination of commands.
Imagine that Julie's tape recorder has a recording function that can record a single command and then re-execute the recorded commands at any time, which is called the Macro command set function. As a result, Julie's recorder system now has four keys, namely, broadcast, rewind, stop and Macro command functions. At this point the design of the system and the previous design has been enhanced, mainly reflected in the Julia class now has a new method to operate the Macro command key.
Source
The system requires an interface that represents a macro command to define the interfaces required for a specific macro command.
Public Interface extends Command { /** * Macro Command Aggregation Management method * Can add a member command * /public void Add (Command cmd); /** * Macro Command Aggregation Management method * Can delete a member command * /public void Remove (Command cmd);
The specific macro command Macroaudiocommand class is responsible for combining individual commands with macro commands.
Public classMacroaudiocommandImplementsMacrocommand {PrivateList<command> commandlist =NewArraylist<command>(); /*** Macro Command Aggregation management method*/@Override Public voidAdd (Command cmd) {commandlist.add (cmd); } /*** Macro Command Aggregation management method*/@Override Public voidRemove (Command cmd) {commandlist.remove (cmd); } /*** Method of execution*/@Override Public voidExecute () { for(Command cmd:commandlist) {cmd.execute (); } }}
Client class Julia
Public classJulia { Public Static voidMain (String[]args) {//Create a Recipient objectAudioplayer Audioplayer =NewAudioplayer (); //To Create a Command objectCommand Playcommand =NewPlaycommand (Audioplayer); Command Rewindcommand=NewRewindcommand (Audioplayer); Command Stopcommand=NewStopcommand (Audioplayer); Macrocommand Marco=NewMacroaudiocommand (); Marco.add (Playcommand); Marco.add (Rewindcommand); Marco.add (Stopcommand); Marco.execute (); }}
The results of the operation are as follows:
Advantages of the command mode
more loosely coupled
The command pattern completely decouples the object that originated the command-the client, and the object that implements the command-that is, the object that initiated the command is completely unaware of who the implementation object is and how it is implemented.
more dynamic Control
The command mode encapsulates the request, and it can be parameterized, queued and journaled dynamically, which makes the system more flexible.
It's a natural compound command.
Command objects in command mode can be easily combined into composite commands, which are macro commands, making the system easier to operate and more powerful.
Better Extensibility
Since the object that initiated the command is fully decoupled from the specific implementation, it is easy to extend the new command, just implement the new command object, then set the specific implementation object to the Command object when assembling, and then you can use the command object, and the existing implementation does not have to change at all.
Command mode for Java design mode