Design Mode notes 06-command mode

Source: Internet
Author: User

Design Mode notes 06-command mode
1 Introduction
In this chapter, we will bring encapsulation to a new realm: encapsulate Method Invocation. That's right. By calling the encapsulation method, we can encapsulate the computing block. Therefore, the object that calls this operation does not need to care about how things are done, as long as you know how to use the encapsulated method to complete it. By calling the encapsulation method, you can also do some clever things, such as logging, or reuse these encapsulation for undo ).
2 Text
2.1 command mode
The background of this chapter is that an electric company requires to develop a remote control to control the switch and volume adjustment functions of household appliances. A Programmable Remote control is provided, with a total of 15 buttons: 7 pairs of on/off buttons and an undo button. There are also many household appliances that will be added later.
The command mode decouples the "Action requestor" and "action performer" objects. In your example, the requester can be a remote control, and the execution object is an instance of one of the vendors. Use "command objects" in your design ". Use command objects to encapsulate requests (such as opening lights) into a specific object (such as a living room lamp object ). Therefore, if you store a command object for each button, you can ask the command object for relevant work when the button is pressed. The remote control does not need to know what the work is, as long as there is a command object that can communicate with the correct object and do the job well. So, look, the remote control is decoupled from the lamp object.
Back to the restaurant mode, we all know how the restaurant works: 1. You, the customer, hand over the order to the waitress. 2. The waitress took the order and placed it at the Order counter. Then he shouted "the order has arrived ". 3. Fast food chefs prepare meals according to orders.
Think of a restaurant as a model of the OO design model, which allows the separation of the "requested object" and "accepted and executed object. For example, for the remote control API, We need to separate the "Send request button code" and "the vendor-specific object that executes the request ". What if every slot of the remote control holds an object like a restaurant order? Then, when a button is pressed, the remote control does not need to know how it happened or what objects are involved.
2.2 From restaurant to command mode
Command

public interface Command {public void execute();}

Implement a command to turn on the electric lamp
// This is a Command, so you need to implement the Command interface public class LightOnCommand implements Command {Light light Light;/** the constructor is passed into a certain lamp (for example, the lamp in the living room ), so that this command can be controlled. * It is then recorded in instance variables. Once brother a Yong execute (), the electric light object becomes the receiver and is responsible for receiving the request. */Public LightOnCommand (Light light) {this. light = light;} // This execute () method calls the on () method of the receiving object (the lamp we are controlling) public void execute () {light. on ();}}

Using the command object, suppose we have a remote control with only one button and corresponding slot, and we can control a device:
/// This is the invoker // public class SimpleRemoteControl {// There is a slot holding the Command, and This Command controls a device Command slot; public SimpleRemoteControl () {} // This method is used to set the slot control command. If the client of this Code wants to change the behavior of the remote control button, this method can be called multiple times. Public void setCommand (Command command) {slot = command;} // when you press this button, this method is called to connect the current Command to the slot, and call its execute () method public void buttonWasPressed () using slot.exe cute ();}}

Simple Test on remote control
// This is the public class RemoteControlTest {public static void main (String [] args) in command mode. {// The remote control is the caller. A command object is passed in to send a request. SimpleRemoteControl remote = new SimpleRemoteControl (); // create a light object, which is the recipient of the request. Light light = new Light (); GarageDoor garageDoor = new GarageDoor (); // create a command here, and then send the receiver to it: LightOnCommand lightOn = new LightOnCommand (light ); garageDoorOpenCommand garageOpen = new GarageDoorOpenCommand (garageDoor); // send the command to the caller remote. setCommand (lightOn); // press the remote button. buttonWasPressed (); remote. setCommand (garageOpen); remote. buttonWasPressed ();}}

2.3 define command mode
In command mode, the "request" is encapsulated into an object to parameterize other objects using different requests, queues, or logs. The command mode also supports unrecoverable operations.
Implement remote control
/// This is the invoker // public class RemoteControl {// at This time, the remote control must process 7 ON and OFF commands and use the corresponding array to record these commands [] onCommands; command [] offCommands; public RemoteControl () {// In the constructor, you only need to instantiate and initialize two open and closed arrays onCommands = new Command [7]; offCommands = new Command [7]; // The NoCommand object is an example of a null obeject. When you do not want to return a meaningful object, empty objects are useful. You can also escape the responsibility for processing null to empty objects. For example, the remote control cannot set meaningful command objects at the factory, so it provides a NoCommand object as a Substitute. When you call its execute () // method, this type of object does not do anything. Command noCommand = new NoCommand (); for (int I = 0; I <7; I ++) {onCommands [I] = noCommand; offCommands [I] = noCommand ;}} /** the setCommand () method must have three parameters: slot location, on command, and off command. * These commands will record the slot positions in the switch array for later use. */Public void setCommand (int slot, Command onCommand, Command offCommand) {onCommands [slot] = onCommand; offCommands [slot] = offCommand ;} // when you press the on or off button, the hardware will call the corresponding method, that is, onButtonWasPushed () or offButtonWasPushed (). Public void onButtonWasPushed (int slot) extends oncommands0000slot0000.exe cute ();} public void offButtonWasPushed (int slot) extends offcommands0000slot0000.exe cute ();} // overwrite toString (), print the command corresponding to each slot. This method will be used later when you test the remote control. Public String toString () {StringBuffer stringBuff = new StringBuffer (); stringBuff. append ("\ n ------ Remote Control ------- \ n"); for (int I = 0; I <onCommands. length; I ++) {stringBuff. append ("[slot" + I + "]" + onCommands [I]. getClass (). getName () + "" + offCommands [I]. getClass (). getName () + "\ n");} return stringBuff. toString ();}}

Implementation command
Public class StereoOnWithCDCommand implements Command {Stereo stereo; public StereoOnWithCDCommand (Stereo stereo) {this. stereo = stereo;} // to implement this request, you need to call three methods of audio: First open it, set it to play CD, and finally set the volume to 11. Public void execute () {stereo. on (); stereo. setCD (); stereo. setVolume (11 );}}

Step-by-Step remote control test
Public class RemoteLoader {public static void main (String [] args) {RemoteControl remoteControl = new RemoteControl (); // create all devices in the appropriate position: Light livingRoomLight = new Light ("Living Room"); Light kitchenLight = new Light ("Kitchen "); ceilingFan ceilingFan = new CeilingFan ("Living Room"); GarageDoor garageDoor = new GarageDoor (""); Stereo stereo = new Stereo ("Living Room"); LightOnCommand livingrolightomon = n Ew LightOnCommand (livingRoomLight); LightOffCommand completion = new LightOffCommand (livingRoomLight); LightOnCommand kitchenLightOn = new LightOnCommand (kitchenLight); LightOffCommand completion = new LightOffCommand (kitchenLight ); ceilingFanOnCommand ceilingFanOn = new CeilingFanOnCommand (ceilingFan); CeilingFanOffCommand ceilingFanOff = new CeilingFanOffCommand (ceilingFan); GarageDoorU PCommand garageDoorUp = new response (garageDoor); GarageDoorDownCommand garageDoorDown = new response (garageDoor); Response response = new response (stereo); StereoOffCommand stereoOff = new StereoOffCommand (stereo ); // now you have all the commands to load them into the remote control slot. RemoteControl. setCommand (0, livingRoomLightOn, livingRoomLightOff); remoteControl. setCommand (1, kitchenLightOn, kitchenLightOff); remoteControl. setCommand (2, ceilingFanOn, ceilingFanOff); remoteControl. setCommand (3, stereoOnWithCD, stereoOff); // here, the toString () method is used to print the slot of each remote control and the specified command System. out. println (remoteControl); // everything is ready. Gradually press the ON and OFF buttons for each slot. RemoteControl. onButtonWasPushed (0); remoteControl. offButtonWasPushed (0); remoteControl. onButtonWasPushed (1); remoteControl. offButtonWasPushed (1); remoteControl. onButtonWasPushed (2); remoteControl. offButtonWasPushed (2); remoteControl. onButtonWasPushed (3); remoteControl. offButtonWasPushed (3 );}}


2.4 don't forget to undo
Redesign Command INTERFACE
public interface Command {public void execute();public void undo();}

Redesign command objects
public class LightOnCommand implements Command {Light light;int level;public LightOnCommand(Light light) {this.light = light;} public void execute() {        level = light.getLevel();light.on();} public void undo() {light.dim(level);}}

Redesign remote control
Public class RemoteControlWithUndo {Command [] onCommands; Command [] offCommands; Command undoCommand; public RemoteControlWithUndo () {onCommands = new Command [7]; offCommands = new Command [7]; command noCommand = new NoCommand (); for (int I = 0; I <7; I ++) {onCommands [I] = noCommand; offCommands [I] = noCommand ;} // There is no "previous command" during initialization, so it is set as a NoCommand object. UndoCommand = noCommand;} public void setCommand (int slot, Command onCommand, Command offCommand) {onCommands [slot] = onCommand; offCommands [slot] = offCommand ;} public void onButtonWasPushed (int slot) extends oncommands[slot0000.exe cute ();/** when you press the button, we get this command, execute it first, and record it in the nudoConmmand instance variable. * Whether it is an ON or OFF command, our processing method is the same. */UndoCommand = onCommands [slot];} public void offButtonWasPushed (int slot) implements offcommands[slot0000.exe cute (); undoCommand = offCommands [slot];} public void undoButtonWasPushed () {// when the Undo button is pressed, we can call the Undo () method of the undoConmmand instance variable to reverse the previous command. UndoCommand. undo ();} public String toString () {StringBuffer stringBuff = new StringBuffer (); stringBuff. append ("\ n ------ Remote Control ------- \ n"); for (int I = 0; I <onCommands. length; I ++) {stringBuff. append ("[slot" + I + "]" + onCommands [I]. getClass (). getName () + "" + offCommands [I]. getClass (). getName () + "\ n");} stringBuff. append ("[undo]" + undoCommand. getClass (). getName () + "\ n"); return stringBuff. toString ();}}

2.5 macro commands
Public class MacroCommand implements Command {Command [] commands; public MacroCommand (Command [] commands) {this. commands = commands;} // when the macro command is executed by the remote control, each command in the number group is executed at one time. public void execute () {for (int I = 0; I <commands. length; I ++) implements commands‑i‑.exe cute () ;}} public void undo () {for (int I = commands. length-1; I> = 0; I --) {commands [I]. undo ();}}}

2.6 advanced usage of command mode
For queue requests and log requests, please read other materials for these two advanced-purpose instances. This book only takes a slight note, but this is the place where the command mode can be used in practical applications, I will have the opportunity to study it further later.
3. Summary of this Chapter
Friends who have played games must be familiar with macros. They may not see the necessary focus macros of wower. Shouting macros are actually composed of commands. The command mode is also widely used in actual projects. What are your experiences with coder?













Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.