1.定义:命令模式----将请求封装成对象,这可以让你使用不同的请求,队列,或者日志请求来参数化其他对象。命令模式也可以支持撤销操作。
2.代码部分
public class Light {
public void on() {
System.out.println("打开电灯");
}
public void off() {
System.out.println("关闭电灯");
}
}
public interface Command {
public void execute();
}
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
}
public class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.off();
}
}
public class SimpleRemoteControl {
private Command command;
public SimpleRemoteControl() {
}
public void setCommand(Command command) {
this.command = command;
}
public void buttonWasPressed() {
command.execute();
}
}
public class Client {
public static void main(String[] args) {
SimpleRemoteControl remote = new SimpleRemoteControl();
Light light = new Light();
Command lightOn = new LightOnCommand(light);// 设置打开电灯命令
remote.setCommand(lightOn);
remote.buttonWasPressed();
System.out.println("---------------------");
Command lightOff = new LightOffCommand(light);// 设置关闭电灯命令
remote.setCommand(lightOff);
remote.buttonWasPressed();
}
}
执行结果:
打开电灯
---------------------
关闭电灯