盒子
盒子
文章目录
  1. 1. 命令接口定义
  2. 2. 遥控器类组合命令
  3. 3. 开灯命令
  4. 4. 测试
  • 5. 输出
  • 命令模式

    命令模式:将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作
    SpringMVC中HandlerMapping方法中HandlerExecutionChain getHandler(HttpServletRequest request)便是典型的Command模式的使用

    1. 命令接口定义

    1
    2
    3
    public interface Command {
    void execute();
    }

    2. 遥控器类组合命令

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    public class SimpleRemoteControl {
    private Command slot;

    public SimpleRemoteControl() {};

    public void setCommand(Command command) {
    slot = command;
    }

    public void buttonWasPressed() {
    slot.execute();
    }

    }

    3. 开灯命令

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    public class LightOnCommand implements Command {
    private Light light;

    public LightOnCommand() {};

    public LightOnCommand(Light light) {
    this.light = light;
    }

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

    其中Light.java为:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public class Light {
    private String roomName;

    public Light() {};

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

    public void on() {
    System.out.println(roomName + "light is on");
    }

    public void off() {
    System.out.println(roomName + "light is off");
    }
    }

    4. 测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public class ComplexCommandTest {

    @Test
    public void testParameterCommand() {
    Light light = new Light("Living Room");
    Command lightOnCommand = new LightOnCommand(light);

    SimpleRemoteControl control = new SimpleRemoteControl();

    control.setCommand(lightOnCommand);
    control.buttonWasPressed();
    }
    }

    5. 输出

    Living Roomlight is on

    支持一下
    扫一扫,支持沈健
    • 微信扫一扫
    • 支付宝扫一扫