What is command mode?
definition: encapsulates a request into an object, allowing you to parameterize the customer with different requests.
Main solution: in a software system, the behavior requester and the behavior is usually a tightly coupled relationship, but in some cases, such as the need to record, undo or redo the behavior, transactions and other processing, this can not resist the change of the tight coupling design is not appropriate.
when to use: in some cases, such as "record, Undo/Redo, transaction," and so on, 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.
How to resolve: call the recipient through the caller to execute the command, in order: Caller → recipient → command.
Key code: define three roles: 1, received true command execution Object 2, command 3, invoker using the Command object's entry
Advantages: 1, reduce the system coupling degree. 2. New commands can be easily added to the system.
Cons: using command mode may cause some systems to have too many specific commands.
Usage Scenarios: command mode can be used where commands are considered, such as: 1, each button in the GUI is a command. 2, Analog CMD.
Note: the system needs to support the undo (undo) operation and Recovery (Redo) operation of the command, or consider using the command mode, see the extension of the command mode.
Command mode in JavaScript
The command pattern is also relatively simple in JavaScript, where the following code is 按钮
命令
used and extracted, so you can use the command pattern in a complex project to deliver code for the interface's code and functionality to different people to write.
Const SetCommand =function(button, command) {Button.onclick=function() {Command.excute ()}}//--------------------The above interface logic is done by a, and the following is done by BConst Menu={updatemenu:function() {Console.log (' Update Menu ')},}const UpdateCommand=function(receive) {return{excute:receive.updateMenu,}}const UpdateCommand= UpdateCommand (menu)//Create commandConst button1= document.getElementById (' button1 ') SetCommand (button1, UpdateCommand)
JS design mode (6) Command mode