Command Pattern)
1. What is the command mode? The command mode encapsulates the details of the method call to decouple the requester and executor. The specific process is as follows: 1. from the perspective of the requester (customer), the requester (customer) sends a request-> caller (system) construct a command object encapsulation request-> the caller calls the specified method of the command object (the request is executed). Obviously, the requester does not know who the executor is, nor the specific execution details. Of course, the requester does not care about this either. It only needs to know that the request has been executed. 2. from the perspective of Executors (lower-layer components), executors (lower-layer components) are called-> executors call internal methods (requests are executed). The executors do not know who the requestor is, the caller is not even clear, but it doesn't matter. The performer only needs to do his job well in the current shard, and there is no need to know the leadership situation. 3. from the perspective of the caller (system), you can call the action of the command object to execute the request when appropriate) the caller does not know who the executor is or the requester. The caller is only responsible for constructing commands and controlling command execution. This is enough. From the above, we can see the low coupling relationship between each object: the requester (customer) and the performer (lower-layer component) are completely decoupled, the intermediary callers do not know the details of the requestor and executors. They are well protected. This is exactly what we want. II. for example, in the real world, any slightly complicated sub-system should have A set of commands, such as the restaurant Operating Mechanism: Customer A comes to the restaurant to order A bowl of noodles (send A request) -> the clerk recorded the ticket (CREATE Command)-> the clerk threw the ticket to the kitchen-> the cook C quickly prepared a bowl of noodles (request to be executed) the customer does not know who will cook the bowl, nor does the clerk at the counter know. The cook does not know who has ordered the bowl, I only know that I can rest after I finish it. Is it very similar to the command mode? We may wish to use code to implement the above mechanism. First, we need a command interface. After all, commands are the core of the command mode. Without commands, everything is a fantasy package CommandPattern; /*** @ author ayqy * defines the Command interface */public interface Command {public abstract void execute (); // you only need to define a uniform execution method} execute commands. Otherwise, only the general does not have a soldier. The restaurant performer is of course the Cook: package CommandPattern; /*** @ author ayqy * defines the Chef base class */public abstract class Chef {// defines the cook's public attributes here/*** defines the cooking method */public abstract void cook (); // define other useful methods here} We also need to implement a specific chef, specialized in the industry: Cook: package CommandPattern;/*** @ author ayqy * defines professional cook */public class NoodlesChef extends Chef {@ Override public void cook () {System. out. println ("prepare a bowl of delicious ramen") ;}} cook the pie: package CommandPattern; /*** @ author ayqy * defines the professional cook */public class PieChef extends Chef {@ Override public void cook () {System. out. println ("a delicious pie");} with a soldier and a general, we also need a complete set of commands: package CommandPattern;/*** @ author Yqy * implement NoodlesCommand */public class NoodlesCommand implements Command {private NoodlesChef chef; // professional cook public NoodlesCommand () {chef = new NoodlesChef ();} @ Override public void execute () {chef. cook (); // call other required methods} package CommandPattern;/*** @ author ayqy * implement the specific PieCommand */public class PieCommand implements Command {private PieChef chef; // The professional cook public PieCommand () {chef = new PieChe F () ;}@ Override public void execute () {chef. cook (); // call other required methods} the preparation is complete, and three restaurants can be opened. the effect example requires a Test class: package CommandPattern;/*** @ author ayqy * to implement the Test class */public class Test {public static void main (String [] args) {System. out. println ("Command Pattern restaurant opened .. "); System. out. println ("first customer Mr. X"); System. out. println ("Mr. X: Hello, I need a bowl of noodles. I'm so hungry"); NoodlesCommand nCmd = new NoodlesCommand (); System. out. println ("clerk at the counter: OK, I have already noted it down, right away"); System. out. println ("counter attendant: Kitchen ~~, "); N0000.exe cute (); System. out. println (" Mr. X: so fast! "); System. out. println (); System. out. println ("Mr. XX, the second customer"); System. out. println ("Mr. XX: Hello, I need a piece of cake, take it for 20 minutes later"); PieCommand pCmd = new PieCommand (); System. out. println ("clerk at the counter: OK, I have already noted down"); System. out. println ("15 minutes later"); System. out. println ("counter attendant: Kitchen ~~, "); PCmd.exe cute (); System. out. println (" Mr. XX: It's time! ") ;}} Result example: 1. the caller (the clerk at the counter) can control the execution time, but the details of the executor (the cook) are completely unclear. the requester (customer) has no idea about the operating mechanism of the restaurant, and does not know whether the order is made by a cook, a waiter, or bought from the next door .. 3. the performer (Cook) does not know the requester's situation at all. He only does his job and does not know anything else. command mode extension 1. macro commands (multiple commands are executed in sequence) can be implemented by defining "Command commands" (The execute method of this special command calls the execute method of several other commands in sequence ..) 2. How can we achieve the cancellation if many customers have ordered a lot of meals and a few customers cannot wait to cancel the order after a while? Maintain a command list, record the created commands, and find the corresponding commands during undo. Execute the Undo operation on the premise that the command object supports undo. We need to make some modifications: package CommandPattern; /*** @ author ayqy * defines the Command interface */public interface Command {public abstract void execute (); // you only need to define a uniform execution method public abstract void undo (); // define a uniform revocation method} the revocation operations of each command may be different, so it is defined as an abstract method, perform specific operations by sub-classes * how do I support multi-step sequential revocation? The restaurant example may not require such a function. In another scenario, the text editor user sent a series of commands to complete some column operations, and later found that this was not required, the user will undo the modification (Ctrl + Z). In this case, we need to perform the opposite operation to restore the content. How can we achieve this? We still need to first implement the undo behavior of each command (execute operations in the reverse order of execute). In addition, we also need a stack to record the operations that have been executed, to support revocation to the initial state 3. for queue requests, we can create a working thread responsible for all operations. Imagine there is a channel where the input is a different command, and the output is the execution result of the command. The working thread may be making a pie at the last moment, I have gone out to buy food next time .. * What are the benefits of doing so? You can limit the operation to several specified threads. 4. log requests are mostly used for the implementation of the database management system. We need to record a series of operations (such as writing them on a hard disk) and read them to restore data in case of system faults. How can this problem be achieved? Use object serialization to save the object (record logs) and deserialize (Restore transactions) as needed. the summary command mode can effectively decouple the requester and executor, and provides some additional benefits (such as support for Undo operations, queue requests, and logging) <original> Yu Qingyang welcome reprint do not need to indicate the original source </original> <Statement> author level limited error is inevitable welcome correction </Statement> <email> 835412398@qq.com exchange can progress </Email>