木心

毕竟几人真得鹿,不知终日梦为鱼

导航

head first 设计模式笔记6-命令模式

 命令模式:将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。这个模式允许我们将动作封装成命令对象,然后可以传递和调用。

  1)命令模式将发出请求的对象执行请求的对象解耦

  2)在被解耦的两者之间式通过命令对象进行沟通的。命令对象封装了接收者和一个或一组动作

  3)调用者通过调用命令对象的execute()发出请求,这会使得接收者的动作被调用

  4)调用者可以接受命令当做参数,甚至在运行时动态地进行

  5)命令可以支持撤销,做法是实现一个undo()方法来回到execute()被执行前的状态

 

 Command

/**
 * 命令接口
 * @author oy
 * @date 2019年9月7日 下午10:25:24
 * @version 1.0.0
 */
public interface Command {
    public void execute();
}

 

  Light

public class Light {
    public void on() {
        System.out.println("on,打开电灯");
    }
    public void off() {
        System.out.println("off,关闭电灯");
    }
}

  

  LightOnCommand:发出请求的对象,将“动作”封装成命令对象

/**
 * 实现打开电灯的命令
 * @author oy
 * @date 2019年9月7日 下午10:26:28
 * @version 1.0.0
 *
 */
public class LightOnCommand implements Command {
    Light light;
    public LightOnCommand(Light light) {
        this.light = light;
    }
    @Override
    public void execute() {
        light.on();
    }
}

 

  LightOffCommand:发出请求的对象,将“动作”封装成命令对象

/**
 * 实现关闭电灯的命令
 * @author oy
 * @date 2019年9月7日 下午10:26:28
 * @version 1.0.0
 */
public class LightOffCommand implements Command {
    Light light;
    public LightOffCommand(Light light) {
        this.light = light;
    }
    @Override
    public void execute() {
        light.off();
    }
}

 

  SimpleRemoteControl:执行请求的对象

/**
 * 遥控器
 * @author oy
 * @date 2019年9月7日 下午10:31:45
 * @version 1.0.0
 */
public class SimpleRemoteControl {
    Command slot;
    
    public SimpleRemoteControl() {}
    
    public void setCommand(Command command) {
        slot = command;
    }
    
    public void buttonWarPressed() {
        slot.execute();
    }
}

 

  测试代码

public static void main(String[] args) {
    SimpleRemoteControl simpleRemoteControl = new SimpleRemoteControl();
    simpleRemoteControl.setCommand(new LightOnCommand(new Light()));
    simpleRemoteControl.buttonWarPressed();
    
    simpleRemoteControl.setCommand(new LightOffCommand(new Light()));
    simpleRemoteControl.buttonWarPressed();
    
}

 

posted on 2019-09-07 22:46  wenbin_ouyang  阅读(195)  评论(0编辑  收藏  举报