C # design mode (15) -- Command (Command Pattern)
I. Preface I have been busy with my work before and I have not updated the design pattern series. Recently, I found that it is essential to understand the design pattern, of course, it is even more important for the application of the design model. It can be said that whether the application design mode is used to measure the technical level of a programmer in the project, because of the implementation of a function, senior engineers and junior engineers both implement the same, but the difference lies in the scalability and maintainability of their functions, that is, whether the code is "beautiful" and readable. However, for better application, we must first understand the various design patterns and their application scenarios, so I still hope to continue to complete the design patterns series, we hope to deepen our understanding of the design model through this summary. II. Introduction to command mode 2.1 the definition of command mode in command mode belongs to the behavior mode of the object. The command mode abstracts an operation or action into an object, and separates the responsibility for issuing a command from that for executing a command. The command mode provides command revocation and restoration functions. 2.2 The structure of the command mode since the command mode separates the responsibility for issuing commands from the responsibility for executing commands, there must be an object in the middle to help the issuing command to convey the command, this allows the recipient of the command to receive and execute the command. For example, when the school starts, the school leader says that the computer school is going to perform military training, and the computer school's students are going to run 1000 meters. The school leader's words are equivalent to a command that he cannot directly send to the students, he must ask the instructor to issue the command and supervise the students to execute the command. In this scenario, the responsibility for issuing commands is the leadership of the school. The leadership of the school acts as the creator of command sending. The responsibility for executing commands belongs to the students and the students act as the receiver of commands, instructors act as command senders or command requestors. However, the essence of the command mode is to abstract each command as an object. The structure of the command mode is shown in. The structure of the command mode shows that it involves five roles: customer role: issue a specific command and determine its receiver. Command role: declares an abstract interface specific command role for all specific command classes: defines a weak coupling between the receiver and the behavior, and calls the corresponding method of the receiver. Requester role: responsible for calling command objects to execute commands. Recipient role: responsible for executing specific actions. 2.3 Implementation of the command mode now, let's use the above military training example to implement a command mode. before implementation, you can refer to the structure diagram of the command mode to analyze the implementation process. In military training scenarios, the specific command is that the student runs 1000 meters. Here the student is the receiver of the command, the instructor is the requester of the command, and the school leader is the sender of the command, that is, the client role. To implement the command mode, an abstract command role must be required to declare the convention, which is represented by an abstract class. The command transmission process is: the sender of the command must know the specific command, receiver, and sender of the command, corresponding to the program, that is, the instance objects of three roles need to be instantiated in the client role. The requester of the command is responsible for calling the method of the command object to ensure the execution of the command. The program, that is, the requester object, must have a member of the command object, and execute the command in the method of the requester object. The specific command is to run 1000 meters, which is naturally the responsibility of the Students. Therefore, it is a member method of the specific command role, and the abstract command class defines the abstract interface of this command. With the above analysis, the implementation code of the specific command mode is as follows: Copy code 1 2 // instructor, responsible for calling the Command object to execute the request 3 public class Invoke 4 {5 public command _ Command; 6 7 public Invoke (command Command) 8 {9 this. _ command = command; 10} 11 12 public void ExecuteCommand () 13 {14 _ command. action (); 15} 16} 17 18 // Command abstract class 19 public abstract class Command 20 {21 // Command should know who the recipient is, therefore, the member variable "extends Er" is 22 protected into Er _ extends er; 23 24 public Command (extends er) 25 {26 this. _ Cycler = Cycler; 27} 28 29 // command execution method 30 public abstract void Action (); 31} 32 33 // 34 public class ConcreteCommand: command35 {36 public ConcreteCommand (Receiver receiver) 37: base (receiver) 38 {39} 40 41 public override void Action () 42 {43 // call the receiving method, because the command is executed by the student 44 _ faster er. run1000Meters (); 45} 46} 47 48 // command recipient -- Student 49 public class Receiver50 {51 public void Run1000Meters () 52 {53 Co Nsole. writeLine ("running 1000"); 54} 55} 56 57 // courtyard leader 58 class Program59 {60 static void Main (string [] args) 61 {62 // initialize consumer er, Invoke, and Command63 consumer er r = new consumer Er (); 64 Command c = new ConcreteCommand (r); 65 Invoke I = new Invoke (c ); 66 67 // The school leader issued the command 68 I. executeCommand (); 69} 70} copy code 3 ,. NET command mode application (reference TerryLee) in ASP. net mvc mode, there is a mode called Front Controller, which is divided into two parts: Handler and Command tree, Handler processes all public logic, receive HTTP Po St or Get request and related parameters, and select the correct Command object based on the input parameters, and then pass the control to the Command object to complete subsequent operations, the Command mode is used. The Handler class is responsible for processing various Web requests and assigning the responsibility of determining the correct Command object to the CommandFactory class. After CommandFactory returns the Command object, Handler calls the Execute method on the Command to Execute the request. The specific implementation is as follows: View Code 4. Use the command mode in the following scenarios: 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 implement the command effect again when needed. The system must specify the request and queue the request at different times. A command object and the original request sender can have different lifecycles. It means that the sender of the original request may no longer exist, and the command object itself may still be active. In this case, the receiver of the command can be either local or another address on the network. The command object can be serialized to the receiver. If a system wants to update all the data messages in the system to the log, so that when the system crashes, it can read the update command of all the data according to the log, re-call the method to execute these commands one by one to restore the data updates made before the system crashes. The system must use the command mode as an alternative to "CallBack (CallBack)" in the object-oriented system. Callback registers a method and then calls it later. 5. Advantages and disadvantages of the command mode enables low coupling between the one sent by the Command and the receiving party, so as to have the following advantages: the command mode makes it easy to add new commands to the system. You can design a command queue to perform Undo and Redo operations on the request. It is easier to write commands into logs. You can aggregate command objects and combine them into synthesis commands. Application of Synthetic imperative synthesis mode. Disadvantages of the command mode: using the command mode may cause the system to have too many specific command classes. This makes the command mode impractical in such a system. 6. To summarize the implementation of the command mode, the main point is to abstract a specific command into a specific command class, add the command requestor role to split the dependencies of the command sender on the command executor. In the preceding military training example, if the command mode is not used, the command sender is strongly coupled with the command receiver. The implementation code is as follows: Copy code 1 // The Master 2 class Program 3 {4 static void Main (string [] args) 5 {6 // There is a tight coupling relationship between the requester and the real-time user of the behavior. 7. Faster er r = new faster Er (); 8 9 r. run1000Meters (); 10} 11} 12 13 public class Receiver14 {15 // operation 16 public void Run1000Meters () 17 {18 Console. writeLine ("running 1000 meters"); 19} 20}