The command pattern emphasizes the encapsulation call , which encapsulates the method invocation. By encapsulating the method call, we can encapsulate the operation block, so the object that calls the operation does not need to be concerned about how things work, they just need to know how to use the wrapping method to do it. By encapsulating the method call, we can also do some very clever things, such as logging, or reusing these packages to implement revocation.
We use the following example to understand the command pattern: we want to design a home appliance automation remote control, the remote control has a number of programmable slots (each slot can be assigned to a different appliance device), each slot corresponds to a pair of switch buttons, the entire remote control also has a whole undo button , as shown in the overall appearance.
Slots can be plugged into multiple household appliances sockets: Televisions, refrigerators, lights, doors, etc., so our system has two difficulties : First, the use of various household appliances different, so the interface provided to them is not the same ; In the future there will be more appliances to join the system .
This time, we are going to use "command mode". The command pattern decouples the "requestor of the action" from the "Performer of the Action" Object . In the above example, the requestor of the action can be a remote control, and the performer of the action can be a class that represents the appliance. How can we do "decoupling"? We need to use " Command object ". With command objects, we can encapsulate a command (such as an electric light bulb) into a specific object (such as a living room lamp object), so if there is a command object for each button, then when the button is pressed, you can ask the command object to do the work. In other words, using command mode, we can create an API (Application programming Interface), load these command objects into a button slot, keep the code of the remote control as simple as possible, and encapsulate the work of the home appliance automation and the objects that do the work in the Command object.
To be Continued ...
Mode of command in design mode