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

设计目的

将”动作的请求者”和”动作的执行者”解耦,甚至他们互相不知道对方的存在。

实现方法

设计一个接口,该接口声明了一些方法(execute/undo),所有的命令都实现了该接口,并以该接口为类型在各类中进行传递,“动作的执行者”只要知道它实现了该接口,就可以调用该命令的方法。

命令模式

将请求封装成对象,这可以让你使用不同的请求、队列、或者日志请求来参数化其他对象。命令模式也可以支持撤销操作。
若想撤销多步,则可以使用一个堆栈来记录命令,执行命令的撤销方法即可。

参考示例

1、命令接口

public interface Command {
    public void execute();
    public void undo();
}

2、具体命令类

public class LightOnCommand implements Command {
    /**
     * 持有一个具体对象的引用
     */
    Light light;

    /**
     * 构造
     *
     * @param light 设置对象
     */
    public LightOnCommand(Light light) {
        this.light = light;
    }

    /**
     * 执行该命令
     */
    @Override
    public void execute() {
        light.on();
    }

    @Override
    public void undo() {
        light.off();
    }
}
public class LightOffCommand implements Command {
    /**
     * 持有一个具体对象的引用
     */
    Light light;

    /**
     * 构造
     *
     * @param light 设置对象
     */
    public LightOffCommand(Light light) {
        this.light = light;
    }

    /**
     * 执行该命令
     */
    @Override
    public void execute() {
        light.off();
    }

    @Override
    public void undo() {
        light.on();
    }
}

3、实体类

public class Light {
    String description;

    public Light(String description) {
        this.description = description;
    }

    /**
     * 具体操作
     */
    public void on() {
        System.out.println("打开" + description + "电灯");
    }

    /**
     * 具体操作
     */
    public void off() {
        System.out.println("关闭" + description + "电灯");
    }
}
public class SimpleRemoteControl {
    /**
     * 命令
     */
    Command slot;

    public SimpleRemoteControl() {
    }

    /**
     * 设置命令
     *
     * @param command 具体的命令类,实现了Command接口
     */
    public void setCommand(Command command) {
        slot = command;
    }

    /**
     * 执行该命令
     */
    public void buttonWasPressed() {
        slot.execute();
    }
}

4、测试类

public class SimpleRemoteControlTest {
    public static void main(String[] args){
        SimpleRemoteControl remote = new SimpleRemoteControl();
        Light light = new Light("厨房");
        LightOnCommand lightOnCommand = new LightOnCommand(light);
        LightOffCommand lightOffCommand = new LightOffCommand(light);
        remote.setCommand(lightOnCommand);
        remote.buttonWasPressed();
        remote.setCommand(lightOffCommand);
        remote.buttonWasPressed();
    }
}

猜你喜欢

转载自blog.csdn.net/u012525096/article/details/80661459