command mode
1. Definition
Encapsulates a request as an object, allowing you to parameterize clients with different requests, queue or log requests, and support undoable operations.
2. Sample code
Using the command mode to simulate booting, the button on the chassis is equivalent to the command object, the motherboard is equivalent to the receiver, and the chassis is equivalent to the Invoker requesting the button command object to execute the boot request.
/*Motherboard interface*/ public interface MainBoard{ //The motherboard has the boot function public void open(); } /*Gigabyte motherboard, the real implementer of the boot command*/ public class GAMainBoard implements MainBoard{ //Real boot command implementation System.out.println("Gigabyte motherboard is now booting, please wait"); System.out.println("Power on..."); System.out.println("Check device..."); System.out.println("Load system..."); System.out.println("The machine is running normally..."); System.out.println("The machine has been opened normally, please operate"); }
/*Command interface*/ public interface Command{ public void execute(); } /* Boot command implementation */ public class OpenCommand implements Command{ //Hold the real command receiver, the mainboard object private MainBoard mainBoard = null; public OpenCommand(MainBoard mainBoard){ this.mainBoard = mainBoard; } //For the command object, transfer the boot operation of the mainboard object public void execute(){ this.mainBoard.open(); } } /*The chassis triggers the command object to initiate a power-on request*/ public class Box{ //boot command object private Command openCommand; public void setOpenCommand(Command openCommand){ this.openCommand = openCommand; } /* Provide the user to use, receive and respond to user requests, which is equivalent to the button being pressed, triggering the method*/ public void openButtonPressed(){ openCommand.execute(); } }
/*Customer boot operation*/ public class Client{ public static void main(String args[]){ //1. Assemble the boot object MainBoard mainBoard = new GAMainBoard(); Command openCommand = new OpenCommand(mainBoard); //2. Set the corresponding commands for the buttons on the chassis Box box = new Box(); box.setOpenCommand(openCommand); //3. Press the power button box.openButtonPressed(); } }
3. Practical application
The key point of the command mode is to encapsulate the request into an object, that is, the command object, and define a unified execution operation interface. This command object can be stored, forwarded, recorded, processed, cancelled, etc. The entire command mode is centered around this The command object is in progress.
The essence of the command pattern: encapsulating requests