命令模式

1. 使用场景

需要分离命令发送者和命令执行者时

2. 实现举例

以面向对象的设计方式实现:按下一个遥控器按钮,一盏灯就会亮。

这里命令发送者是遥控器,命令执行者是灯,命令对象负责在两者之间传递请求:

interface Command { void execute(); } class Remote { private Command[] commands; public Remote(Command[] commands) { this.commands = commands; } public void pushButton(int n) { if (n < 0 || n >= commands.length) { System.out.println("没有那个按钮"); return; } commands[n].execute(); } } class Light { public void on() { System.out.println("灯亮了,一切明亮了起来"); } public void off() { System.out.println("灯灭了,转瞬间回归黑暗"); } }

测试:

// 一盏灯 Light light = new Light(); // 一个遥控器,有开关两个命令 Remote remote = new Remote(new Command[] { () -> light.on(), () -> light.off() }); // 测试 remote.pushButton(0); // 按下0按钮 remote.pushButton(1); // 按下1按钮

results matching ""

    No results matching ""