The command mode of Java design mode

Source: Internet
Author: User

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 patterndefinitionPasses a request from the client to an object, allowing you to parameterize the customer with different requests. For the "behavior requestor" and "The behavior realization" decoupling, can achieve the loose coupling between the two, in order to adapt to the change. Separation of changes and invariant factors.
rolecommand defines the interface of the commands, declaring the method to execute. The Concretecommand command interface implements the object, which is the implementation of "virtual", usually holding the receiver and invoking the function of the receiver to complete the operation that the command performs. Receiver receiver, the object that actually executes the command. Any class can become a recipient, as long as it can implement the appropriate functionality that the command requires. Invoker requires the command object to execute the request, usually holding the command object, which can hold a lot of command objects. This is where the client actually triggers the command and asks the command to perform the appropriate action, which is equivalent to using the Command object's entry. The client creates a specific command object and sets the recipient of the Command object. Note that this is not our regular client, but the assembly of the Command object and the receiver, and perhaps it would be better to refer to this client as the assembler, since the client that actually uses the command is triggering execution from Invoker.
Advantages1. Reduce the coupling between the objects. 2. New commands can be easily added to the system. 3. It is easier to design a combination command. 4. Call the same method to implement different functions
DisadvantagesUsing command mode may cause some systems to have too many specific command classes. Because you need to design a specific command class for each command, some systems may require a large number of specific command classes, which will affect the use of the command pattern.
Where applicable1. The system needs to decouple the requesting caller from the request receiver so that the caller and receiver do not interact directly. 2. The system needs to specify requests at different times, queue requests, and execute requests. 3. The system needs to support the undo (undo) operation and Recovery (Redo) operation of the command. 4. The system needs to combine a set of operations, that is, macro commands are supported.

  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

Package com.bankht.command;/** * @author: Commando-ak47 * @ Created: 2012-7-2 Morning 11:41:21 *  @ class Description: Recipient role Class */public class Receive R {/** * really executes the command corresponding to the action */public Void action () {System.out.println ("perform operation");}}

Abstract command Role Class

Package com.bankht.command;/** * @author: Commando-ak47 * @ Created: 2012-7-2 Morning 11:42:00 *  @ class Description: Abstract command role Class */public interface Co Mmand {/** * Execute method */void execute ();}


Specific command role classes

Package com.bankht.command;/** * @author: Commando-ak47 * @ Created: 2012-7-2 Morning 11:42:23 *  @ class Description: Specific command role class */public class Concre Tecommand implements Command {//holds the corresponding recipient object Private receiver receiver = null;/** * Construction method */public Concretecommand (receiver R Eceiver) {this.receiver = receiver;} @Overridepublic void Execute () {//will normally transpose the corresponding method of the recipient object, allowing the receiver to actually perform the function receiver.action ();}}


Requestor role Class

Package com.bankht.command;/** * @author: Commando-ak47 * @ Created: 2012-7-2 Morning 11:42:45 *  @ class Description: Requestor role class */public class Invoker {/** * holds command object */private commands = null;/** * Constructor method */public Invoker (Command command) {this.command = command;} /** * Action method */public void action () {Command.Execute ();}}



Client Role Classes

Package com.bankht.command;/** * @author: Commando-ak47 * @ Created: 2012-7-2 Morning 11:41:21 *  @ class Description: Recipient role Class */public class Receive R {/** * really executes the command corresponding to the action */public Void action () {System.out.println ("perform operation");}}


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

Package com.bankht.command.recorder;/** * @author: Commando-ak47 * @ Created: 2012-7-2 pm 02:30:19 *  * class Description: Receiver role, played by Sound Recorder class */pub Lic class Audioplayer {public void play () {System.out.println ("play ..."); public void Rewind () {System.out.println ("rewind ..."); public void Stop () {System.out.println ("stop ...");}}


Abstract command Role Class

Package com.bankht.command.recorder;/** * @author: Commando-ak47 * @ Created: 2012-7-2 pm 02:30:44 *  @ class Description: Abstract command role class */public int Erface Command {/** * Execute method */public void execute ();}


Specific command role classes

Package com.bankht.command.recorder;/** * @author: Commando-ak47 * @ Created: 2012-7-2 pm 02:31:27 *  @ class Description: Specific command role class-broadcast */public  Class Playcommand implements Command {private Audioplayer myaudio;public Playcommand (Audioplayer audioplayer) {Myaudio = Audioplayer;} /** * Execute method */@Overridepublic void execute () {Myaudio.play ()}}

Package com.bankht.command.recorder;/** * @author: Commando-ak47 * @ Created: 2012-7-2 pm 02:32:40 *  @ class Description: Specific command role class-Rewind */public Class Rewindcommand implements Command {private Audioplayer myaudio;public Rewindcommand (Audioplayer audioplayer) { Myaudio = Audioplayer;} @Overridepublic void Execute () {myaudio.rewind ();}}


Package com.bankht.command.recorder;/** * @author: Commando-ak47 * @ Created: 2012-7-2 pm 02:33:25 *  @ class Description: Specific command role class-Stop */public  Class Stopcommand implements Command {private Audioplayer myaudio;public Stopcommand (Audioplayer audioplayer) {Myaudio = Audioplayer;} @Overridepublic void Execute () {myaudio.stop ();}}


Requestor role, played by keyboard class

Package com.bankht.command.recorder;/** * @author: Commando-ak47 * @ Created: 2012-7-2 pm 02:35:52 *  @ class Description: Requestor role, played by keyboard class */publ IC class Keypad {private command playcommand;private command rewindcommand;private command stopcommand;public void Setpla Ycommand (Command playcommand) {this.playcommand = Playcommand;} public void Setrewindcommand (Command rewindcommand) {this.rewindcommand = Rewindcommand;} public void Setstopcommand (Command stopcommand) {this.stopcommand = Stopcommand;} /** * Perform playback method */public void Play () {Playcommand.execute ();} /** * Perform rewind method */public void Rewind () {Rewindcommand.execute ();} /** * Execute playback method */public void Stop () {Stopcommand.execute ();}}


Client role, played by Julie Little girl

Package com.bankht.command.recorder;/** * @author: Commando-ak47 * @ Created: 2012-7-2 pm 02:36:17 *  @ Class Description: Client role, played by Julie Little girl */pu Blic class Julia {public static void main (string[] args) {//Create receiver object Audioplayer Audioplayer = new Audioplayer ();//create Command object C Ommand Playcommand = new Playcommand (Audioplayer); Command Rewindcommand = new Rewindcommand (Audioplayer); Command Stopcommand = new Stopcommand (audioplayer);//create requestor object keypad keypad = new keypad (); Keypad.setplaycommand ( Playcommand); Keypad.setrewindcommand (Rewindcommand); Keypad.setstopcommand (Stopcommand);//test Keypad.play (); Keypad.rewind (); Keypad.stop (); Keypad.play (); Keypad.stop ();}}




The results of the operation are as follows:

[HTML]View Plaincopyprint?
    1. Play...
    2. Rewind with ...
    3. Stop it...
    4. Play...
    5. Stop it...
Play... Rewind with ... Stop it... Play... Stop it...


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.

Package com.bankht.command.recorder;/** * @author: Commando-ak47 * @ Created: 2012-7-2 pm 02:46:04 *  @ Class Description: The system requires an interface that represents a macro command. To define the interface required for a specific macro command. */public Interface Macrocommand extends command {/** * Macro command Clustered 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.

Package Com.bankht.command.recorder;import java.util.arraylist;import java.util.list;/** * @author: Commando-ak47 * @ Created on: 2012-7-2 PM 02:46:38 *  * Class Description: The specific macro command Macroaudiocommand class is responsible for the individual commands to synthesize the macro command. */public class Macroaudiocommand implements Macrocommand {private list<command> commandlist = new arraylist< Command> ();/** * Macro Command Aggregation Management method */@Overridepublic void Add (command cmd) {commandlist.add (cmd);} /** * Macro Command Aggregation Management method */@Overridepublic void Remove (command cmd) {commandlist.remove (cmd);} /** * Execution method */@Overridepublic void execute () {for (Command cmd:commandlist) {Cmd.execute ()}}}



Client Class Juliahong

Package com.bankht.command.recorder;/** * @author: Commando-ak47 * @ Created: 2012-7-2 pm 02:48:06 *  @ Class Description: Client class Juliahong */pub Lic class Juliahong {public static void main (string[] args) {//Create receiver object Audioplayer Audioplayer = new Audioplayer ();//create command Object command Playcommand = new Playcommand (Audioplayer); Command Rewindcommand = new Rewindcommand (Audioplayer); Command Stopcommand = new Stopcommand (Audioplayer); Macrocommand Marco = new Macroaudiocommand (); Marco.add (Playcommand); Marco.add (Rewindcommand); Marco.add (StopCommand ); Marco.add (Stopcommand); Marco.add (Stopcommand); Marco.execute (); System.out.println ("--------Ornate dividing Line----------------"); Marco.remove (Playcommand); Marco.remove (Stopcommand); Marco.execute ();}}


The results of the operation are as follows:

    1. Play...
    2. Rewind with ...
    3. Stop it...
    4. Stop it...
    5. Stop it...
    6. --------Gorgeous split-line----------------
    7. Rewind with ...
    8. Stop it...
    9. Stop it...
Play... Rewind with ... Stop it... Stop it... Stop ...--------gorgeous split-line----------------Rewind ... Stop it... Stop it...


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.

This article draws on blogs:

Http://www.cnblogs.com/java-my-life/archive/2012/06/01/2526972.html

Http://www.cnblogs.com/java-my-life/archive/2012/06/01/2526972.html

Http://blog.csdn.net/column/details/loveyun.html

Copyright NOTICE: Welcome reprint, Hope in your reprint at the same time, add the original address, thank you with

The command mode of Java design mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.