hf-ch6- command mode

0. Order

I do not know how to write a preface met a pattern not previously encountered.

See the end of this chapter is really too stiff, the back will attach my practice codes in this chapter!

1. Command Mode

The command mode "request" encapsulated in objects, in order to use a different request, parameterized log queue or other objects, command mode also supports undoable operations.

Command Mode may be "Action requester" decoupling from "action executive" object. For example: After the button is pressed, the remote control on the lamp should open, then the remote controller to achieve the object there is directly involved in causing lamp coupling. -> How Decoupling -> encapsulating the request (e.g., turn on the light) to a particular object, then, if the button to store a command object, so when the button is pressed, the command object may accordingly work without knowing What content yes.

Examples: restaurant guests ordering, the waiter took the order, the waiter put the order into the window, according to the order cooks prepare meals. Here the order that is encapsulated meal request (issue the command), the waiter delivered the order to the window (command transfer), where the waiter does not need to know what is on order, has orders to whom. Chefs prepare meals (command implementation).

Use empty object refers not do anything of the object, you can avoid the judgment in using this type of an object if(command!=null) command.execute();using a null object just call the execute () can, if it is empty, then it will not do anything (p214)

class OneCommand implements Commend{
    execute(){
        //执行方法语句
        
        ....
    }
}
class NoCommand implements Commend{
    execute(){
   //这里是空的
    }
}

More use command mode: schedule (Scheduler) work queue thread pool, log requests, etc.

2. Exercise Code

Personal mode because before this chapter has not been exposed, had not fully understand the process of reading the feeling had finished combing the code later in this chapter

Examples: implement remote control

public class Light {
    public   void  on(){
        System.out.println("灯亮了");
    };
    public   void  off(){
        System.out.println("灯灭了");
    };
}
//先不使用命令模式 对一个遥控器该如何实现
/**
 * 假设遥控器有三个槽
 * 每个槽对应开 关 两个按钮 on off
 */
public class 遥控器 {
    private String slot1;//槽1
    private String slot2;//槽1
    private String slot3;//槽1
    public void slot1OnExecute(){
        if (slot1==Light){
            Light.on();
        }else if (slot1==Door){
            Door.on();
        }....
    }
    ...
}
//很显然 这里会有很多if-else 并且如果新增加一个槽的功能,就要加一个if-else 不好维护

Therefore, command mode, the remote control instruction encapsulated -Command, the method of performing a package with an execute (), performed after obtaining the Command object execute () command to complete

/**
 * 封装命令的对象
 */
public interface Command {
    void execute();//执行方法
}

/**
 * 灯亮
 */
public class LightOnCommand  implements Command{
    private  Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.on();
    }
}
/**
 * 遥控器
 */
public class RemoteControl {
    Command slot;//一个槽对应一个命令的执行 这里以一个槽为例

    public RemoteControl() {
    }

    public void setSlot(Command slot) {
        //设置每个槽对应的指令
        this.slot = slot;
    }
    public void button1_1Pressed(){
        //槽被按下 执行该槽的方法
        slot.execute();
    }
}


//测试
   public static void main(String[] args) {
        RemoteControl re=new RemoteControl();
        Light light =new Light();
        LightOnCommand lightOnCommand=new LightOnCommand(light);
        re.setSlot(lightOnCommand);
        re.button1_1Pressed();
    }

To achieve a plurality of grooves with a remote control and an undo command on the revocation operation, the idea of the book is very simple, to come up with a variable on a record command, if the revocation method of the variable press undo record command is executed, where I also want to revoke undo, if you want to achieve this function, then you need to record and undo functions corresponding to the slot number .

Advanced undo function, status revoked - fans of "low, medium and high" third gear

/**
 * 风扇类
 */
public class CeilingFan {
    public static final int HIGH=3;
    public static final int MEDIUM=2;
    public static final int LOW=1;
    public static final int OFF=0;
    String location;
    int speed; //记录当前的速度状态
    public CeilingFan(String location){
        this.location=location;
        speed=OFF;
    }
    public void high(){
        System.out.println("当前执行:"+ location+ " HIGH");
        speed=HIGH;
    }
    public void medium(){
        System.out.println("当前执行:"+ location+ " MEDIUM");
        speed=MEDIUM;
    }
    public void low(){
        System.out.println("当前执行:"+ location+ " LOW");
        speed=LOW;
    }
    public void  off(){
        System.out.println("当前执行:"+ location+ " OFF");
        speed=OFF;
    }

    public int getSpeed() {
        return speed;
    }
}

//高命令 中 低 关闭命令类似
public class CeilingFanHighCommand  implements Command {

    CeilingFan ceilingFan;
    int prevSpeed;//之前的速度 作为撤销命令使用

    public CeilingFanHighCommand(CeilingFan ceilingFan){
        this.ceilingFan=ceilingFan;
    }

    @Override
    public void execute() {
        prevSpeed=ceilingFan.getSpeed();
        ceilingFan.high();
    }

    @Override
    public void undo() {
        if (prevSpeed==CeilingFan.HIGH)
            ceilingFan.high();
        else  if (prevSpeed==CeilingFan.MEDIUM)
            ceilingFan.medium();
        else if (prevSpeed==CeilingFan.LOW)
            ceilingFan.low();
        else if (prevSpeed==CeilingFan.OFF)
            ceilingFan.off();
    }
}

//测试
        CeilingFan ceilingFan_room=new CeilingFan("房间");

        CeilingFanHighCommand ceilingFanHighCommand=new CeilingFanHighCommand(ceilingFan_room);
        CeliFanMediumCommand celiFanMediumCommand=new CeliFanMediumCommand(ceilingFan_room);
        CeliFanLowCommand celiFanLowCommand=new CeliFanLowCommand(ceilingFan_room);
        CeliFanOffCommand celiFanOffCommand=new CeliFanOffCommand(ceilingFan_room);
        

        advancedRemoteControl.setCommand(4,ceilingFanHighCommand,celiFanOffCommand);
        advancedRemoteControl.setCommand(5,celiFanMediumCommand,celiFanOffCommand);
        advancedRemoteControl.setCommand(6,celiFanLowCommand,celiFanOffCommand);
        advancedRemoteControl.hasOnButtonWasPressed(4);//高
        advancedRemoteControl.hasOnButtonWasPressed(5);//中
        advancedRemoteControl.undoButtonWasPressed();
        
当前执行:房间 HIGH
当前执行:房间 MEDIUM
当前执行:房间 HIGH

3. Extended

Take a trip down to find the command mode is actually a bunch of commands encapsulated (packaged as a command) the caller only needs to be performed to execute command () can be, do not need to be concerned about how to implement the order, and do not care about the order recipient , decoupling. I.e., the fan is a receiver, the open / fan speed command is the command encapsulated into such instructions (Command), the process in order to package the recipient has been determined (constructor forms) of the command, and then in command button corresponding to the remote controller (the caller), as long as the button is depressed on the implementation of execute () method.

Command mode more uses: Request Queue - packed command processing blocks (including instructions and a receiver in the fast operation), and then passed around him, until the call. So "schedule (scheduler), thread pools, work queues", which are the principle.

Here Insert Picture Description

In this case, between the working class and queue thread operations are completely decoupled , thread execution queue only execute () method can be, without relation to the object is performed to read data or network mathematical calculations.

Here Insert Picture Description

Released nine original articles · won praise 4 · Views 4244

Guess you like

Origin blog.csdn.net/qq_42239081/article/details/105361950