6.命令模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cuicanxingchen123456/article/details/84306636

Head-First-Design-Patterns-master\src\headfirst\designpatterns\command

把方法调用封装起来,可以把运算块包装成形。

定义:将“请求”封装成对象,以便使用不同的请求,队列或者日志来参数化其他对象,命令模式也支持可撤销的操作。

例子:餐厅订餐

public class Light{
    public void on();
    public void off();
}
public interface Conmmand{
    public void execute();
}

public class LightOnCommand implements Command{
    Light light;
    public LightOnCommand(Light light){
        this.light=light    
    }
    public void execute(){
        light.on();
    }
}
public class SimpleRemoteControl{
    Command slot;
    publicSimpleRemoteControl(){}
        public void setCommand(Command command){
            slot=command;
        }
        public void buttonWasPressed(){
            slot.execute();
        }
}
public class RemoteControlTest{
    public static void main(String[] args){
       SimpleRemoteControl remote=new SimpleRemoteControl();
             Light  light=new Light();
             LightOnCommand lightOn=new LightOnCommand(light);
             remote.setCommand(lightOn);
             remote.buttonWasPressed();
    }
}

上面是最基础的代码,可以实现如灯(灯打开命令,灯关闭命令),灯中加入(厨房灯,大厅灯),可以实现电扇的打开,关闭命令。

可以使用command[]来加载所有的命令,然后定义遥控器类

public class RemoteControl {
    Command[] onCommands;
    Command[] offCommands;
    Command undoCommand;
    public RemoteControl() {
        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;
        }
        undoCommand = noCommand;
    }
  
    public void setCommand(int slot, Command onCommand, Command offCommand) {
        onCommands[slot] = onCommand;
        offCommands[slot] = offCommand;
    }
    public void onButtonWasPushed(int slot) {
        onCommands[slot].execute();
        undoCommand = onCommands[slot];
    }
    public void offButtonWasPushed(int slot) {
        offCommands[slot].execute();
        undoCommand = offCommands[slot];
    }
    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();
    }
}

还可以加入宏命令功能和撤销功能。

命令模式的更多用途

如scheduler,线程池,工作队列,日志请求等

将命令放入队列中,线程从队列中取出命令,执行命令的command之后继续拿下一个命令。

猜你喜欢

转载自blog.csdn.net/cuicanxingchen123456/article/details/84306636