命令模式

01 定义

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

02 情景

通过电灯开关的按钮来控制电灯的打开或者关闭。

03 类图

CommandPattern.png

04 Class

// 灯:Receiver 接收者,真正执行命令的对象。
public class Light {
    private String name;
    public Light(String name) {
        this.name = name;
    }
    // 开灯
    public void on(){
        System.out.println(String.format("The %s light is on", name));
    }
    // 关灯
    public void off(){
        System.out.println(String.format("The %s light is off", name));
    }
}
// 定义命令的接口
public interface Command {
    public void execute();
}
// 开灯命令: 命令接口实现对象,是“虚”的实现;通常会持有接收者(Light),并调用接收者的功能来完成命令要执行的操作。
public class LightOnCommand implements Command {
    private Light light;
    public LightOnCommand(Light light) {
        this.light = light;
    }
    @Override
    public void execute() {
        light.on();
    }
}
// 关灯命令: 命令接口实现对象,是“虚”的实现;通常会持有接收者(Light),并调用接收者的功能来完成命令要执行的操作。
public class LightOffCommand implements Command {
    private Light light;
    public LightOffCommand(Light light) {
        this.light = light;
    }
    @Override
    public void execute() {
        light.off();
    }
}
// Invoker:调用器
// 要求命令对象执行请求,通常会持有命令对象,可以持有很多的命令对象。
// 这个是客户端真正触发命令并要求命令执行相应操作的地方,也就是说相当于使用命令对象的入口。
public class RemoteControl {
    private Command command;
    public void setCommand(Command command){
        this.command = command;
    }
    public void pressButton(){
        command.execute();
    }
}

05 测试

// Client:创建具体的命令对象,并且设置命令对象的接收者。
Light light = new Light("Living room");
LightOnCommand lightOnCommand = new LightOnCommand(light);
LightOffCommand lightOffCommand = new LightOffCommand(light);

RemoteControl remoteControl = new RemoteControl();
// 开灯
remoteControl.setCommand(lightOnCommand);
remoteControl.pressButton();
// 关灯
remoteControl.setCommand(lightOffCommand);
remoteControl.pressButton();
TestResult.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容