What is Command mode?
concept
The Command Pattern is a behavioral Pattern that encapsulates a request as an object so that you can parameterize customers with different requests. Queue or log requests, and support undoable operations. The command mode is decoupled and can be delayed. For example, threads are a good example of command mode. If the command mode is not applicable, then we cannot give the method we want to execute to the thread.
For example, we go to a restaurant, the waiter will bring us a menu, the menu is already written “command”, only need to talk to waiter (requestor) we want to eat what food (command), the waiter will inform chef (implementer) what to do, we think food enough, also can cancel without cooking; When we want to change the channel, we pick up the remote control (requester), press the button (command) on another channel, the TV (implementer) changes the channel, and we want to go back to watch directly click back.
In fact I also have been thinking about it, “we” in these two examples is in a what kind of role, “we” is the role of this module is in command mode, we want to implement demand has to call the requester, as I take your order, you directly say with chef, chef where often, and it was useless to you directly to the TV shout. Here we can also see that the requester encapsulates how the command is used, and we only need to interact with the requester to use it.
The command mode is also very similar to the Windows or Linux command operation interface, we only need to enter commands and parameters, can execute the function.
advantages
- Reduce coupling of the system. The coupling between requester and implementer is reduced by introducing objects such as commands.
- In line with the principle of openness and closure. To add new operations, simply write a new command class.
- You can defer execution, undo, and queue requests.
Most design patterns are designed to understand coupling, high cohesion, and I’m getting a little tired of writing about it.
disadvantages
- Increased system complexity. The use of command mode may cause the system to produce a large number of command classes, each operation has to implement a corresponding command class, a large number of command classes will increase the complexity of the system.
- Reduced code readability. Using command mode is to separate requester and implementer by command, which not only brings difficulties in code design, but also increases the difficulty of understanding the system.
Most design patterns are difficult to implement and add complexity to the system.
The principle of
“+” for compliance, “-” for non-compliance or irrelevant
The principle of | Open the closed | Single responsibility | Di milt | Replacement on the Richter scale | Dependency inversion | Interface segregation | Synthesis of reuse |
---|---|---|---|---|---|---|---|
+ | + | – | – | + | – | – | |
Applicable scenario
- Event-driven modules. Like a browser button or an operating system console, an action or a line of command is triggered to perform the action.
- Requires decoupling of requester and implementer. Requester and implementer do not interact directly.
- Execution can be delayed, undone, or rolled back. Things like logging and saving information to a database.
How to implement
To implement command mode, you need the following four things:
- Abstract command interface: Used to declare commands and has an abstract method execute () to execute commands.
- Concrete command class: implements abstract command interfaces and calls implementers to complete functions.
- Implementer/receiver class: provides services for concrete command classes.
- Requester/caller class: The caller of a command, responsible for managing and executing the command.
On the class diagram
Here I copy the command pattern class diagram seen at other sites. You can take a look at it, and then you can look at the code THAT I wrote.
The example
Summer is coming, every household is equipped with air conditioning, there is an air conditioning installation and maintenance of the company, the leadership of the company is responsible for the installation and maintenance of air conditioning workers, workers to receive work after installation and maintenance.
Class diagram:
Code:
/** * Created on 2021/6/4. * * @author xuxiaobai */ public class CommandTest { public static void main(String[] args) { // Leader Leader =new Leader(); Worker = new Worker(" Worker "); System.out.println(" leader arranges work "); Leader.addplan (new InstallWork("A town 58 ", worker)); AddPlan (New RepairWork(" no. 23 in TOWN B ", worker)); // The leader cancels the leader.cancel(); AddPlan (new InstallWork("C 15 ", worker)); // Rearrange leader.addplan (new InstallWork("C 15 ", worker)); Leader.addplan (new InstallWork("D town 8 ", worker)); Leader.addplan (new InstallWork(" etown 6 ", worker)); System.out.println(" leader gives command "); leader.order(); /** * result: * The leader arranges the work * cancelling the work arrangement * the leader issues the order * Zhang SAN rides on the beloved van, arrives at the C town 15 * Zhang SAN begins the work * dismounts the air conditioner * installs the inside machine * installs the outside machine * checks * finishes the work * Zhang SAN rides on the beloved van, Arriving at D town no. 8 * Zhang SAN started work * unloaded air conditioning * installed inside machine * installed outside machine * inspection * finished work * Zhang SAN got on his beloved van, Arrived at no. 6, E town * Zhang SAN started work * unloaded air conditioner * installed inside machine * installed outside machine * inspection * finished work */}} /** * */ class Worker{private String name; Private Boolean airConditioner=false; public Worker(String name){ this.name=name; } /** * arrive destination * @param address */ public void arrive(String address){system.out.print (name+" on the bus, arrive "); System.out.println(address); / / public/airConditioner (){this. AirConditioner =true; / / private airConditioner (){this. AirConditioner =false; / / public void installAirConditioner(){system.out.println (name+" start working "); System.out.println(" remove air conditioner "); putAirConditioner(); System.out.println(" insert machine "); System.out.println(" out.println "); System. The out. Println (" test "); System.out.println(" finish "); /** * repairAirConditioner(){public void repairAirConditioner(){system.out.println (name+" start working "); System.out.println(" unplug "); System. The out. Println (" check "); System.out.println(" remove inner shell "); System. The out. Println (" check "); System. The out. Println (" maintenance "); System.out.println(" finish "); Void execute();}} /** * interface Work{void execute(); } /** * InstallWork implements Work{// private String address; // private Worker Worker; Private Boolean voucher=false; public InstallWork(String address,Worker worker){ this.address=address; this.worker=worker; this.voucher=true; } @override public callback () {if (voucher){worker.getairconditioner (); }else {system.out. println(" no air conditioner, no air conditioner "); return; } worker.arrive(address); worker.installAirConditioner(); /** * RepairWork */ class RepairWork implements Work{// address private String address; // private Worker Worker; public RepairWork(String address,Worker worker){ this.address=address; this.worker=worker; } @Override public void execute() { worker.arrive(address); worker.repairAirConditioner(); Class Leader{List<Work> works=new ArrayList<>(); class Leader{List<Work> works=new ArrayList<>(); Public void addPlan(work){work.add (work); } public void order(){Iterator<Work> Iterator = works.iterator(); while (iterator.hasNext()){ Work work = iterator.next(); work.execute(); iterator.remove(); }} /** * cancel */ public void cancel(){system.out.println (" cancel "); works.clear(); }}Copy the code
We have a brief look, it is ok to arrange the train of thought.
If the command mode is not used, we have to operate the Worker object directly, and we have to operate all the steps without delay. With command mode, we can even create command classes using factories, which makes it much easier to use.
conclusion
The key to the command pattern is that it encapsulates the request/operation as a command object, which is written in advance and then handed to the implementer to complete the operation, which can be undone or added before the command is executed.
When I was learning command mode, I was always wondering what is the difference between command mode and write method? The direct write method also encapsulates the operation logic, but in this way you cannot delay execution, undo, and rollback.
— — — — — — — — — — — — — — —
The more you know, the more you don’t know.
If you have any questions about the content of this article, please comment directly or email me. If you think my writing is good, a “like” is also a sign of support
Shall not be reproduced without permission!