-- [Advantages: 1. Reduce coupling between objects. 2. New commands can be easily added to the system. 3. You can easily design a combined command. 4. Call the same method to implement different functions. Disadvantage: using the command mode may cause some systems to have too many specific command classes. Because a specific command class needs to be designed for each command, some systems may need a large number of specific command classes, which will affect the use of the command mode. Command class: it is an abstract class that declares the commands to be executed. Generally, an execute method should be published to execute commands. ConcreteCommand class: The Implementation class of the Command class, which implements the methods declared in the abstract class. Invoker class: caller, responsible for calling commands. Receiver class: Receiver, responsible for receiving and executing commands.] -- Command = {} function Command: new (r, o) o = o or {} setretriable (o, self) self. _ index = self o. extends ER = r return o; end ConcreteCommand1 = Command: new () function ConcreteCommand1: Execute () self. operator Er: Action1 () end ConcreteCommand2 = Command: new () function ConcreteCommand2: Execute () self. operator Er: Action2 () end operator ER = {} function operator Er: new (o) o = o or {} setretriable (o, self) self. _ index = self return o; end function runner Er: Action1 () print ("") end function runner Er: Action2 () print (" ") end Invoker = {} function Invoker: new (o) o = o or {} setretriable (o, self) self. _ index = self o. allcommand = {} return o; end function Invoker: SetCommand (c) table. insert (self. allcommand, c) end function Invoker: ExecuteCommand () for _, v in pairs (self. allcommand) do v: Execute () end -- the cook is chef = cheer: new () -- The following are two dishes (commands), and the performer is cheer (chef) fish = ConcreteCommand1: new (chef) cake = ConcreteCommand2: new (chef) -- the caller is the waiter = Invoker: new () -- the waiter has issued two dishes (commands), and the executor is of course chef) waiter: SetCommand (fish) waiter: SetCommand (cake) -- it seems that the waiter has made two dishes. Actually, it is done by the handler, which decouples them. The guests and chefs do not need to closely couple with each other. waiter: executeCommand ()
Output result: Come to a steamed fish cake exchange group: 315249378 if any is incorrect, please discuss it!