C # design mode 14 command pattern "behavioral"

Source: Internet
Author: User

Original: C # design mode 14 command pattern "behavioral"

First, Introduction

Today we begin to talk about the second pattern of the "behavioral" design pattern, which is the "command pattern", also known as action mode or trading (Transaction) mode, with the English name: command pattern. Or the old routine, first look at the name. "Command mode" the first time I saw the name, my understanding was that it might be an action or an action is a command. The word "command" is used most in the army, for example: to give orders for combat, and then to be on the battlefield. Based on these, I feel that "command" is the task, executed the command to complete a task. In other words, the command is a task, and we do not know from this name who the issuer and the recipient are, and for what? Because we do not care who they are, the person who issued the order, can continue to do other things, accept the order of the people to carry out the task, do not need you to give orders, but also to supervise us to complete, as long as we complete the task is qualified on the line. This behavior is also "decoupling". In our real life there are many examples to illustrate this pattern, we also take dumplings this thing to say. My grandmother said, want to eat dumplings today, issued an order, and then my grandmother went to watch TV. Our husband and wife received orders to start noodles, dumplings stuffing, dumplings. Dumplings wrapped, we will take a rest, and so on 5 o'clock in the afternoon began to boil boiled dumplings, supper time, my grandmother on time to eat dumplings. There are many other examples that are not listed.

Ii. Detailed description of the command mode

2.1. Motive (motivate)

In the process of software building, "behavior requestor" and "behavior realization person" usually present a kind of "tight coupling". But in some cases-such as the need to conduct "record, Undo/Redo (Undo/redo), transaction" and other processing, this can not resist the change of tight coupling is inappropriate. In this case, how do you decouple the "behavior requestor" from the "behavior-implementing Person"? By abstracting a set of behaviors into objects, you can achieve loose coupling between them.

2.2. Intention (Intent)

Encapsulates a request as an object, allowing you to parameterize the client (the client and the requester of the behavior) with different requests, queue up requests or log requests, and support revocable operations. --"Design pattern" GoF

2.3. structure diagram (Structure)



2.4, the composition of the model

As you can see from the structure diagram of the command pattern, it involves five roles, namely:

(1), Customer role (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.

(2), command role: declares an abstract interface that is implemented for all specific command classes.

(3), specific command role (Concretecommand): The command interface implements the object, which is the implementation of the "virtual", usually holding the receiver and invoking the function of the receiver to complete the operation to be performed by the command.

(4), requestor role (Invoker):Requires the command object to execute the request, usually holding the command object, and 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.

(5), Recipient role (Receiver): The recipient, 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.

2.5, the code implementation of the command mode

The following is to eat dumplings in life for example, how to implement the command mode it. In real life, as the northern people love to eat dumplings, my grandmother especially love to eat dumplings, I also inherited this hobby. This morning, my grandmother issued an order that she would like to eat pork and onion stuffing dumplings. My grandmother's legs are not good, let my father take a message to our husband and wife, the evening to eat pork and onion stuffing dumplings. I realized in a moment that this great task fell on the shoulders of our husband and wife. Say do, guarantee dinner can eat steaming dumplings, the specific implementation code is as follows:

1 namespaceimplementation of the command pattern2 {3     /// <summary>4     ///as the saying goes: "Delicious than dumplings, comfortable rather than inverted." Today Grandma spoke to eat his big grandson and Sun-daughter-in-law dumplings. Today also takes dumplings this matter to say the command pattern realization. 5     /// </summary>6     classClient7     {8         Static voidMain (string[] args)9         {Ten             //grandma wants to eat pork and onion stuffing dumplings OnePatrickliuandwife Liuandlai =NewPatrickliuandwife ();//Command Recipient ACommand command =NewMakedumplingscommand (Liuandlai);//Command -Papainvoker Papa =NewPapainvoker (command);//command Requestor -  the             //Grandma issued an order - Papa. ExecuteCommand (); -  -  + Console.read (); -         } +     } A  at     //This type is the requester's role--my father's role, telling Grandma to eat dumplings . -      Public Sealed classPapainvoker -     { -         //The orders my father received from his grandmother. -         PrivateCommand _command; -  in         //Dad started to take specific orders. -          Publicpapainvoker (Command command) to         { +              This. _command =command; -         } the  *         //dad gave us orders . $          Public voidExecuteCommand ()Panax Notoginseng         { - _command. Makedumplings (); the         } +     } A  the     //the type is the abstract command role--commmand, which defines the abstract interface of the command, the task is to package dumplings +      Public Abstract classCommand -     { $         //the recipient of a real mission $         protectedPatrickliuandwife _worker; -  -         protectedCommand (patrickliuandwife worker) the         { -_worker =worker;Wuyi         } the  -         //This method is the Execute method of abstract Command object Wu          Public Abstract voidmakedumplings (); -     } About  $     //the type is the specific command role--concretecommand, this command completed making "pork and onion stuffing" dumplings -      Public Sealed classMakedumplingscommand:command -     { -          PublicMakedumplingscommand (Patrickliuandwife worker):Base(worker) {} A  +         //Execute order--dumplings the          Public Override voidmakedumplings () -         { $             //Execute order---dumplings the_worker. Execute ("today, the package is the farm pork and peasant onion stuffing dumplings"); the         } the     } the  -     //the type is the specific command to accept the role receiver, the specific dumplings are the behavior of our husband and wife to complete in      Public Sealed classPatrickliuandwife the     { the         //This method is equivalent to the receiver type of the action method About          Public voidExecute (stringjob) the         { the Console.WriteLine (Job); the         } +     } -}


This model is a bit complicated, it is not very well understood at the beginning, this mode in our actual coding is not a lot, may be targeted to specific areas of the software or system needs more, such as: Document editing and so on. Take a closer look at the coding process and see the code's structure and patterns in use. There are some variants of this pattern, and some characters can be merged or omitted. I write this code implementation, there is no prominent command of redo and undo, nor write commands queued, but you should know that the reason to abstract the behavior of independent objects, is to be able to do special processing.

Three, the implementation of the command mode points:

1, the basic purpose of the command mode is to decouple the "behavior requestor" from the "behavior realization", in object-oriented language, the common means of implementation is "abstract behavior as Object".

2, the command interface to implement the specific commands object Concretecommand sometimes may save some additional state information as needed.

3. By using composite combination mode, multiple commands can be encapsulated as a "composite command" Macrocommand.

4. The command mode is somewhat similar to the delegate in C #. But the two definitions of the behavior interface are different: The command defines the behavior interface specification in object-oriented "interface-implementation", which is more strict and more conform to the abstract principle; delegate defines the behavior interface specification with a function signature, which is more flexible but less abstract.

5. Using command mode causes some systems to have too many specific command classes. Some systems may require dozens of, hundreds of or even thousands of specific command classes, which makes the command pattern impractical in such a system.

3.1 ", the advantages of the command mode:

(1), the command mode makes it easy for new commands to be added to the system.

(2), you can design a command queue to implement the undo and redo operations on the request.

(3), the command can be more easily written to the log.

(4), the command object can be aggregated together, synthesized as a synthesis command. The application of synthetic command-style synthesis mode.

3.2 ", the disadvantage of the command mode:

(1), using the command mode may cause the system to have too many specific command classes. This makes the command pattern impractical in such a system.

3.3 ", Command mode usage scenario:

(1), the system needs to support the revocation of the command (undo). The Command object can store the state and wait until the client needs to undo the effect of the command, and call the Undo method to undo the effect of the command. The Command object can also provide a redo method for the client to re-implement the command effect when needed.

(2), the system needs to specify the request at different times, queue the request. A Command object and the original request issuer can have a different life cycle. This means that the issuer of the original request may no longer exist, and the command object itself may still be active. At this point the recipient of the command can be local or another address on the network. Command objects can be routed serially to the recipient.

(3), if a system to update all the data messages in the system to the log, so that in the event of a system crash, you can read back all the data in the Log Update command, recall the method to execute the command one at a time, so as to restore the system before the crash of data updates.

(4), the system needs to use the command mode as "CallBack (callback)" in the object-oriented system of substitution. Callback is to register a method first, and then call the method later.

Iv. Implementation of the command pattern in. NET

Because. NET has delegate, it seldom uses command. It uses delegate to do as long as it needs to use behavioral abstraction. Because this is the framework, it is less relevant to the business area of the infrastructure level, it is not necessary to use the OO level. For us, we suggest more command to achieve.

v. Summary

Today, it is time to pick up the children from school, the little boy just went to school, a little naughty, do not want to go to school, haha, this and I was very similar when I was a child. The command pattern is the abstraction of an action or behavior into a separate object, which separates the responsibility for issuing the command from the responsibility for executing the command by abstracting the command, as well as the special operation of the individual Command object, such as the ability to undo and redo the command.

C # design mode 14 command pattern "behavioral"

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.