python-Command mode

Source: Internet
Author: User

Description

The command is activated at the sender and is responded to on the receiving side. An object can be either the sender of a command or the receiver of a command, or both. The typical application of commands is the development of graphical user interfaces. Each form contains a menu, a toolbar, a button, and other controls, the user's stand-alone action is also called the command as an external event, and then the system according to the bound event handler executes the corresponding action is the command to obtain a response to complete the user's request.

In most cases, the caller and receiver of a command are pre-bound, but when you want to manipulate the command, you need to undo the tight coupling between the caller and receiver of the command, making them independent.

Command pattern: Encapsulates a request as an object, as a mediator between the command caller and the receiver, and the abstract command object makes it possible to perform special operations on a series of requests, such as queuing a request or logging a request log, and supporting undoable operations.

Structure Composition:

command role, specific command role, recipient role, requestor (caller) role (Invoker), Client role (client)

Instance:

In most hotels, when the waiter has received the customer's order, entered into the system, according to different dishes, there will be different background reaction. For example, hotels have cold dishes, hot dishes, staple food, that when the waiter will be the food input into the system, the cold dishes will print out the customer points of cold dishes, hot dishes will print out the customer points of hot dishes, staple food will print out the staple items. So how is the backend mode of this system designed? Of course, add if...else directly in the scene code ... Sentence judgment is a method, but this once again aggravated the system coupling, violating the principle of single responsibility, when the system needs change, it will easily violate the opening and closing principle. So we need to reorganize the structure. The system can be designed to the front desk attendant system and back-Office system, the back-end system is further subdivided into staple subsystem, cold dish subsystem, hot dish subsystem.

#staple subsystem, cold dish subsystem, hot dish subsystem, backstage three subsystemsclassBacksys ():defCook (self,dish):PassclassMainfoodsys (backsys):defCook (self,dish):Print("Mainfood:cook%s"%dish)classCooldishsys (backsys):defCook (self,dish):Print("Cooldish:cook%s"%dish)classHotdishsys (backsys):defCook (self,dish):Print("Hotdish:cook%s"%dish)#Front desk attendant system and backstage system interaction, we can through the command mode to achieve,#The waiter will be the customer's order of the contents of the order, directly to the background orders, the background to complete the command requirements,#The foreground system is built as followsclassWaitersys (): Menu_map=dict () commandlist=[]    defSetorder (self,command):Print("Waiter:add Dish") self.commandList.append (command)defCancelorder (self,command):Print("waiter:cancel Order ...") self.commandList.remove (command)defNotify (self):Print("waiter:notify ...")         forCommandinchSelf.commandList:command.execute ()#the Notify interface in the foreground system invokes the Execute interface in the command directly, executing the command. Command class BuildclassCommand (): Receiver=Nonedef __init__(self, receiver): Self.receiver=receiverdefExecute (self):PassclassFoodcommand (Command): Dish=""    def __init__(self,receiver,dish): Self.receiver=receiver Self.dish=DishdefExecute (self): Self.receiver.cook (self.dish)classMainfoodcommand (foodcommand):PassclassCooldishcommand (foodcommand):PassclassHotdishcommand (foodcommand):Pass"""The command class is a comparative class, Foodcommand class is the class involved in this example, compared to the command class has been a certain transformation. Since the execution function in the backend system is cook, the Execute interface is implemented directly in the Foodcommand class, and if the execution function of the background system is different, the Execute interface needs to be implemented in three sub-command systems. In this way, three command classes in the background can be inherited directly without modification. """#menu-type ancillary ServicesclassMenuall:menu_map=dict ()defLoadMenu (self):#Load menu, here to write dead directlyself.menu_map[" Hot"] = ["Yu-shiang Shredded Pork","sauteed Tofu, Home Style","sauteed Snow peas"] self.menu_map["Cool"] = ["Cucumber","Preserved Egg"] self.menu_map["Main"] = ["Susan","Pie"]    defIshot (self,dish):ifDishinchself.menu_map[" Hot"]:            returnTruereturnFalsedefIscool (self,dish):ifDishinchself.menu_map["Cool"]:            returnTruereturnFalsedefIsmain (self,dish):ifDishinchself.menu_map["Main"]:            returnTruereturnFalse#Business Scenariosif  __name__=="__main__": Dish_list=["Yu-shiang Shredded Pork","sauteed Tofu, Home Style","Cucumber","Susan"]#customer-ordered disheswaiter_sys=Waitersys () Main_food_sys=Mainfoodsys () Cool_dish_sys=Cooldishsys () Hot_dish_sys=Hotdishsys () menu=Menuall () menu.loadmenu ( ) forDishinchdish_list:ifMenu.iscool (dish): cmd=Cooldishcommand (cool_dish_sys,dish)elifMenu.ishot (dish): cmd=Hotdishcommand (hot_dish_sys,dish)elifMenu.ismain (dish): cmd=Mainfoodcommand (main_food_sys,dish)Else:            Continuewaiter_sys.setorder (cmd) waiter_sys.notify ()

Printing results:

Waiter:add Dish
Waiter:add Dish
Waiter:add Dish
Waiter:add Dish
Waiter:notify ...
Hotdish:cook Yu-shiang Shredded Pork
Hotdish:cook sauteed Tofu, Home Style
Cooldish:cook Cucumber
Mainfood:cook Rice

Pros: Reduce the coupling between objects. New commands can be easily added to the system. It is easier to design a combination command. Calling the same method to implement different functionality disadvantages: Using the command pattern 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. Applicability:

The system needs to decouple the requesting caller from the request receiver so that the caller and receiver do not interact directly.

Specify, arrange, and execute requests at different times.

Support for modifying logs, undoing operations.

The system needs to combine a set of operations that support macro commands.

python-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.