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

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

 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();
    
}

猜你喜欢

转载自www.cnblogs.com/xy-ouyang/p/11483618.html