——将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。
interface Command {
public void execute();
}
class Light {
public void on() {
System.out.println("light on");
}
public void off() {
System.out.println("light off");
}
}
class LintOnCommand implements Command {
Light light;
public LintOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
}
class SimpleRemoteControl {
Command command;
public SimpleRemoteControl() {}
public void setCommand(Command command) {
this.command = command;
}
public void buttonWasPressed() {
command.execute();
}
}
public class Test {
public static void main(String[] args) {
SimpleRemoteControl control = new SimpleRemoteControl();
Light light = new Light();
LintOnCommand onCommand = new LintOnCommand(light);
control.setCommand(onCommand);
control.buttonWasPressed();
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章