Code farmer Xiao Wang-design mode-command mode

Source: Internet
Author: User

The example of the big talk design pattern speaks very well, the understanding also is convenient! Sometimes forget. It is especially cool to think of these special examples.

Grilled kebabs bring the thought!
Roadside stand-up kebabs:
Boss, I have a row here first Ah, I first give money. The boss is not familiar with this. My is spicy Ah! The boss did not put salt! Scene confusion, has not been clear who is who's ah, too many people. The quality of the barbecue is also affected, the mood is not good ah. The roast man's mood was influenced by the customer.
Barbecue in the shop
Waiter, give me two skewers, 2 chicken wings, two bottles of beer.
Chicken wings do not have, point other bar, Meat essence Bar. A little spicy.

The comparison between the two:
Roadside business instability, often is that a few times, the source is not fixed, people more chaotic, so business is not stable. Barbecue when everyone wants to eat first, barbecue boss a person, so busy chaos ah. All people have no things, all staring at here, barbecue more that a string, test good, everyone is relatively clear.
What's the relationship here?
tight Coupling
The tight coupling between the client and the butcher's boss makes it easy to make mistakes and mess up, and it's easy to pick up. Here is the tight coupling between the requester of the act and the perpetrator of the act. we need to record which few people's kebabs, there is no special request (spicy not spicy), paid no, who first who after AH. This is the request to do what oh. Make a record of the request Oh, that is the log.
If someone asks for a withdrawal request, or if someone asks for a re-bake, what is it actually?
undo and Redo.
So, all requests are queued or logged, a section supports actions that can be undone, and so on. The tight coupling between the requester and the provider of the behavior is not too appropriate.

Let's talk about the barbecue.
We do not know the roast meat master, see have not seen. We just need to give the receptionist the waiter a good word. She gave us a record and then handed the order to the master. There are orders, there must be order. No mess, no forgetting.
Waiter, too much meat, give me a bunch of good? The waiter drew a pen on the order. Fix it, then inform the master. let the waiter decouple the coupling between our client and the grill .
Programming into life!

Our abstract commands

//抽象命令    publicabstractclass Command    {        protected Barbecuer receiver;//烤肉串的执行者        publicCommand(Barbecuer receiver)        {            this.receiver = receiver;        }        //执行命令        abstractpublicvoidExcuteCommand();    }

The implementation of this command class, what is the test? Test ham, muscle, or something else?

//Kebab orderClass Bakemuttoncommand:command { Public Bakemuttoncommand(Barbecuer Receiver):Base(receiver) { } Public Override void Excutecommand() {receiver.        Bakemutton (); }    }//Grilled chicken wings commandClass Bakechickenwingcommand:command { Public Bakechickenwingcommand(Barbecuer Receiver):Base(receiver) { } Public Override void Excutecommand() {receiver.        Bakechickenwing (); }    }

What are we doing with the barbecue?

//烤肉串者    publicclass Barbecuer    {        publicvoidBakeMutton()        {            Console.WriteLine("烤羊肉串!");        }        publicvoidBakeChickenWing()        {            Console.WriteLine("烤鸡翅!");        }    }

There is also an important figure is our waiter, this decoupling of the important tool. Waiter order is to let our barbecue ah, or some other things to carry out, the last time can be executed.

    //服务员    publicclass Waiter    {        private Command command;        //设置订单        publicvoidSetOrder(Command command)        {            this.command = command;        }        //通知执行        publicvoidNotify()        {            command.ExcuteCommand();        }    }

Finally, how do we do it?

              //Pre-opening preparationBarbecuer boy =NewBarbecuer (); Roast man Command bakeMuttonCommand1 =NewBakemuttoncommand (boy); Create a roast what, who's going to bake it? That's the roast. Command BakeMuttonCommand2 =NewBakemuttoncommand (boy); Command BakeChickenWingCommand1 =NewBakechickenwingcommand (boy); Waiter girl =NewWaiter ();//Open for businessGirl. Setorder (BAKEMUTTONCOMMAND1);//Next order, let our master to carry outGirl.Notify(); Girl.            Setorder (BAKEMUTTONCOMMAND2); Girl.Notify(); Girl.            Setorder (BAKECHICKENWINGCOMMAND1); Girl.Notify();

This procedure must be still a problem, how can the real situation like this? can only order one dish at a time, notice once.
Second, we don't know if there's anything else in the kitchen? We should check the astringent and let our waiter
Third, our customers have ordered what dishes we should do record, after a good fee, there may be customer service in the middle of the cancellation of the things within.

Waiter, there's a list of orders.

     Public classWaiter {Privateilist<command> orders =NewList<command> ();//Set up orders         Public void Setorder(Command command) {if(command.) ToString () = ="Command mode. Bakechickenwingcommand ") {Console.WriteLine ("Waiter: Chicken Wing No, please order other barbecue." "); }Else{orders.                ADD (command); Console.WriteLine ("Add Order:"+ command. ToString () +"Time:"+ DateTime.Now.ToString ()); }        }//Cancel Order         Public void Cancelorder(Command command) {orders.            Remove (command); Console.WriteLine ("Cancel Order:"+ command. ToString () +"Time:"+ DateTime.Now.ToString ()); }//Notification full execution         Public void Notify()        {foreach(Command cmdinchOrders) {cmd.            Excutecommand (); }        }    }

The process of execution is just the same as ours, so don't worry.

Command mode: Commands encapsulate one of our requests as an object, allowing you to parameterize customer service using different requests, queue or log requests, and support actions that can be undone.
Let's take a look at our pictures.

Command commands 5 roles in design mode:
(1). Customer role: Creates a specific command object and determines its recipient.
Barbecuer boy = new Barbecuer (); The Roast man.
Command bakeMuttonCommand1 = new Bakemuttoncommand (boy); Order, the roast man is the recipient

(2). Command role: declares an abstract interface to all specific command classes. This is an abstract role, usually implemented by a Java interface or Java abstract class.
This is our command above, and our waiter depends on him. We have to have a command clerk to call our kitchen.

(3). Specific command roles: Defines a weak coupling between a receiver and a behavior, implements the Execute method, and is responsible for invoking the corresponding operation of the receiver. The Execute method is often called the execution method.
It's good to understand that our method relies on our specific executor, the roast man. Which method does the roast man have? What are we baking?

(4). Requestor (Invoke) role: responsible for invoking the Command object execution request, the related method is called the action method.
This is the equivalent of our waiter Oh, right!

(5). 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.

The specific executor of each of our orders is him, he's the boss of the barbecue.

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 operation, and the command requests a request to perform an action, the command receiver receives the request, and executes the action. The command mode allows the command requester and the command receiver to be independent, so that the command requester does not have to know the interface of the command receiver, not to know how the request was received, and whether the operation was executed, when it was executed, and how it was executed.

Waiter

//请求者角色  class Invoker{          private Command command;          publicInvoker(Command command){                  this.command = command;          }          publicvoidaction(){                  command.execute();          }  

Grilled meat.

//接收者  class Receiver{  //行动方法          publicvoidaction(){                  System.out.println("Action has been taken.");          }  }  

The waiter relies on the command, the command depends on our recipient, the person who grilled the meat. This will indirectly convey the word!

//抽象命令角色  interface Command{      void execute();  }  //具体命令类  class ConcreteCommand implements Command{          private Receiver receiver;          public ConcreteCommand(Receiver receiver){                  this.receiver = receiver;          }          publicvoid execute(){                  receiver.action();        }  }  

What about the customer service side?

//client   Public  class  client{public  static  void  main  ( String[] (args) {//Client creation command Recipient  receiver receiver = new  Receiver ();             //client to create a specific command and specify the command recipient           Command command = new  concretecommand (receiver);             //the client creates the requestor and assigns a specific command to the requestor           Invoker Invoker = new  Invoker (command);              //command requestor to issue a command request  invoker.action (); }   }   

The advantages and disadvantages of command design patterns:
Pros: decouple The contact between the command requester and the recipient. The requestor invokes a command, and the recipient accepts the request and performs the corresponding action, since the requestor does not need to know any interface of the recipient by using Command mode decoupling.
Cons: Causes the occurrence of too many specific command classes.

Code farmer Xiao Wang-design mode-command 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.