Command mode: Command (converted from aliang. Net)

Source: Internet
Author: User
Command mode is the behavior mode of an object [gof95 ]. The command mode is also called action mode or transaction mode. In command mode, a request or operation is encapsulated into an object. The command mode allows the system to parameterize the client using different requests, queue requests or record request logs, and provides command revocation and recovery functions.

Command mode is the encapsulation of commands. The command mode separates the responsibility for issuing commands from the responsibility for executing commands and delegates them to different objects.

Each Command is an operation: the Requesting Party sends a request to execute an operation; the receiving party receives the request and performs the operation. The command mode allows the requester and the receiver to be independent, so that the requester does not have to know the interfaces of the receiver, or how the request is received, and whether the operation is executed, when it is executed, and how it is executed.

Ii. Structure of the command mode

The class diagram of the command mode is as follows:

The command mode involves five roles:

Client role: Creates a concretecommand object and determines its receiver.
Command role: declares an abstract interface for all specific command classes. This is an abstract role.
Concretecommand role: defines the weak coupling between a receiver and behavior, implements the execute () method, and is responsible for calling the corresponding operations of the acceptance test. The execute () method is usually called the execution method.
The invoker role is used to call a command object to execute a request. The related method is called the action method.
Receiver role: Implements and executes a request. Any class can be the receiver. The method for implementing and executing requests is called the action method.

Iii. Schematic diagram of the command modeSource code

 

 // Command pattern -- Structural example  Using System; // "Command"  Abstract   Class Command { // Fields    Protected Receiver receiver; // Constructors    Public Command (receiver ){ This . Cycler = Cycler ;} // Methods   Abstract   Public   Void Execute ();} // "Concretecommand"  Class Concretecommand: Command { // Constructors    Public Concretecommand (extends er extends ER ): Base (Cycler ){} // Methods    Public   Override   Void Execute () {executor er. Action ();}} // "Cycler"  Class Explorer { // Methods    Public   Void Action () {console. writeline ("Called runner er. Action ()" );}} // "Invoker"  Class Invoker { // Fields    Private Command command; // Methods    Public   Void Setcommand (command ){ This . Command = command ;} Public   Void Executecommand () {command. Execute ();}} /**/ /// <Summary> /// Client Test  /// </Summary>  Public   Class Client { Public  Static   Void Main ( String [] ARGs ){ // Create aggreger, command, and invoker Explorer r = New Extends Er (); command c = New Concretecommand (r); invoker I = New Invoker (); // Set and Execute Command I. setcommand (c); I. executecommand ();}}

Iv. Emperor Yu Chuan Mei Monkey King heaven

The command mode is not a new invention. It was created before the Monkey King made a noise. At that time, the Yudi command was too white and Venus called the Monkey King to heaven: "Venus enters (Water Curtain Cave), and the South decided: 'I am the west too white Venus, and I am offering the sacred purpose of the Yudi. Please go big in the lower bound, worship xianlu. '"Yu Di is the system client, Taibai Venus is the sender of the command, Monkey King is the receiver of the command, and the holy command is the command. This command of Yudi requires the Monkey King to report to the upper bound. The Jade Emperor only sends commands, no matter how the commands are delivered to the Monkey King. Venus in Taibai is responsible for transmitting the holy decree, but how the Monkey King executes the holy decree and when it will be the Monkey King's own affairs. Otherwise, the Monkey King of JIU Mei will make a big noise in tiangu.

The simulation system is designed as follows:

V. Implementation of the command mode

First, the command should be "heavy" or "light. You can make different choices under different circumstances. If the command is designed to be "light", it only provides a coupling between the requester and the receiver. The command indicates that the requester implements the request.

On the contrary, if you design a "heavy" command, it should implement all the details, including the operations represented by the request, instead of the receiver. This method can be used when a system has no receiver.

What is more common is the situation between two extremes of the least "light" and the most "heavy. The command class dynamically determines which receiver class to call.

Second, whether undo and redo are supported. If a command class provides a method, such as unexecute (), to restore the effect of its operations, the command class supports undo and redo. The specific command class needs to store status information, including:

1. The recipient object actually implements the operation represented by the request;
2. parameters required for operations on the recipient object;
3. Initial status of the receiver class. The receiver must provide an appropriate method so that the command class can call this method so that the receiver class can restore its original state.

If you only need to provide an undo and redo layer, the system only needs to store the last command object to be executed. To support multiple levels of Undo and redo, the system needs to store the list of commands that have been executed, the maximum length allowed by the list is the number of Undo and redo layers supported by the system. The reverse command (unexecute () that executes the commands in the list is undo; the reverse command in the list is redo.

Vi. Practical Use Cases of command mode

The followingCodeThe command mode demonstrates a simple calculator and allows the execution of Undo and redo. Note: "operator" is a keyword in C #. Therefore, add "@" to change it to an identifier.

 // Command pattern -- real world example  Using System; Using System. collections; // "Command"  Abstract   Class Command { // Methods    Abstract   Public   Void Execute (); Abstract   Public   Void Unexecute ();} // "Concretecommand"  Class Calculatorcommand: Command { // Fields    Char @ Operator ; Int Operand; calculator; // Constructor    Public Calculatorcommand (calculator, Char @ Operator ,Int Operand ){ This . Calculator = calculator; This .@ Operator = @ Operator ; This . Operand = operand ;} // Properties    Public   Char Operator { Set {@ Operator = Value ;}} Public   Int Operand { Set {Operand = value ;}} // Methods    Override   Public  Void Execute () {calculator. Operation (@ Operator , Operand );} Override   Public   Void Unexecute () {calculator. Operation (undo (@ Operator ), Operand );} // Private helper Function    Private   Char Undo ( Char @ Operator ){ Char Undo = '' ; Switch (@ Operator ){ Case   '+' : Undo = '-' ; Break ; Case   '-' : Undo = '+' ; Break ; Case   '*' : Undo = '/' ; Break ; Case   '/' : Undo = '*' ; Break ;} Return Undo ;}} // "Cycler"  Class Calculator { // Fields   Private   Int Total = 0; // Methods    Public   Void Operation ( Char @ Operator , Int Operand ){ Switch (@ Operator ){ Case   '+' : Total + = operand; Break ; Case   '-' : Total-= operand; Break ; Case   '*' : Total * = operand;Break ; Case   '/' : Total/= operand; Break ;} Console. writeline ( "Total = {0} (following {1} {2 })" , Total ,@ Operator , Operand );}} // "Invoker"  Class User { // Fields    Private Calculator calculator = New Calculator (); Private Arraylist commands = New Arraylist (); Private   Int Current = 0; // Methods   Public   Void Redo ( Int Levels) {console. writeline ( "---- Redo {0} levels" , Levels ); // Perform redo operations      For ( Int I = 0; I <levels; I ++) If (Current <commands. Count-1) (command) commands [current ++]). Execute ();} Public   Void Undo ( Int Levels) {console. writeline ( "---- Undo {0} levels" , Levels ); // Perform undo operations      For (Int I = 0; I <levels; I ++) If (Current> 0) (command) commands [-- current]). unexecute ();} Public   Void Compute ( Char @ Operator , Int Operand ){ // CREATE command operation and execute it Command command = New Calculatorcommand (calculator ,@ Operator , Operand); command. Execute (); // Add command to undo list Commands. Add (command); current ++ ;}} /**/ /// <Summary>/// Commandapp Test  /// </Summary>  Public   Class Client { Public   Static   Void Main ( String [] ARGs ){ // Create user and let her compute User user = New User (); User. Compute ( '+' , 100); User. Compute ( '-' , 50); User. Compute ( '*' , 10); User. Compute ( '/' , 2 ); // Undo and then redo some commands User. Undo (4); User. Redo (3 );}}

7. Under what circumstances should I use the command mode?

The command mode should be considered in the following situations:

1. Use the command mode as an alternative to "Callback" in the object-oriented system. "Callback" refers to registering a function and then calling it later.

2. You must specify the request at different times and queue the request. A command object and the original request sender can have different lifecycles. In other words, the original request sender may no longer exist, and the command object itself is still active. At this time, the command receiver can be local or another address on the network. The command object can be transmitted to another machine after being serialized.

3. The system must support undo commands ). The command object can store the status. When the client needs to revoke the effect of the command, it can call the Undo () method to cancel the effect of the command. The command object can also provide the Redo () method for the client to re-execute the command when needed.

4. If a system wants to update all the data in the system to the log, you can read all the data update commands in the log and call execute () again when the system crashes () to restore the data updates made by the system before the crash.

5. A system must support transactions ). A transaction structure encapsulates a set of data update commands. Using the command mode to implement the transaction structure can add a new transaction type to the system.

8. advantages and disadvantages of using command mode

The command allows the requester and the recipient to evolve independently and has the following advantages:

The command mode makes it easy to add new commands to the system.
The requesting party is allowed to decide whether to reject the (veto) request.
It is easier to design command queues.
It can easily implement the Undo and redo of the request.
You can easily log commands as needed.
The command mode separates the object requesting an operation from the object that knows how to execute an operation.
The command class can be modified and promoted like any other class.
You can aggregate command objects and combine them into synthesis commands. For example, macro commands are examples of merging commands. The merging command is an application of the merging mode.
Since adding a new command class does not affect other classes, it is easy to add a new command class.
The disadvantages of the command mode are as follows:

Using the command mode will cause some systems to have too many specific command classes. Some systems may need dozens, hundreds, or even thousands of specific command classes, which will make the command mode impractical in such systems.

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.