设计模式学习笔记——命令模式

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


设计模式学习笔记——命令模式_第1张图片

实现命令接口
public interface Command {
    public void execute();
    public void undo();
}
目标类以及命令封装
public class Light {
    private String name;
    
    public Light(String name) {
        this.name = name;
    }  
    public void on(){
        System.out.println(name+" Light is on!");
    }
    public void off(){
        System.out.println(name+" Light is off!");
    }
}
public class LightOnCommand implements Command {
    Light light;
    public LightOnCommand(Light light) {
        this.light = light;
    }

    public void execute() {
        light.on();
    }

    public void undo() {
        light.off();
    }
}
public class LightOffCommand implements Command {
    Light light;
    
    public LightOffCommand(Light light) {
        this.light = light;
    }

    public void execute() {
        light.off();
    }
    
    public void undo() {
        light.on();
    }
}
实现一个空命令
public class NoCommand implements Command {
    public void execute() {}
}
遥控器类
public class RemoteControl {
    Command[] onCommands;
    Command[] offCommands;
    Command undoCommand; // 前一个命令

    public RemoteControl() {
        onCommands = new Command[6];
        offCommands = new Command[6];

        Command noCommand = new NoCommand();
        for(int i = 0; i < 6; i++) {
            onCommands[i] = noCommand;
            offCommands[i] = noCommand;
        }
        undoCommand = noCommand;
    }

    public void setCommand(int pos, Command onCommand, Command offCommand) {
        onCommands[pos] = onCommand;
        offCommands[pos] = offCommand;
    }

    public void onButtonWasPushed(int pos) {
        onCommands[pos].execute();
        undoCommand = onCommands[pos];
    }

    public void offButtonWasPushed(int pos) {
        offCommands[pos].execute();
        undoCommand = offCommands[pos];
    }

    public void undoButtonWasPushed() {
        undoCommand.undo();
    }
}
Client
public class Client {
    public static void main(String[] args) {
        RemoteControl remoteControl = new RemoteControl();
        
        Light livingRoomLight = new Light("Living Room");

        LightOnCommand livingRoomLightOn =
                    new LightOnCommand(livingRoomLight);


        LightOffCommand livingRoomLightOff =
                    new LightOffCommand(livingRoomLight);

        remoteControl.setCommand(0, livingRoomLightOn, livingRoomLightOff);

        remoteControl.onButtonWasPushed(0);
        remoteControl.offButtonWasPushed(0);
        remoteControl.undoButtonWasPushed();        
    }
}

输出结果如下:

Living Room Light is on!
Living Room Light is off!
Living Room Light is on!

你可能感兴趣的:(设计模式学习笔记——命令模式)