命令模式:将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作
案例:用户和多调节灯案例,并且用栈实现多撤销
代码:图里面没有画出栈,我在User里加了记录命令执行的栈,然后Light里家里灯的几个状态
public interface Command {
public void execute();
public void undo();
}
public class Light {
public static final int LOW = 0;
public static final int MID = 1;
public static final int HIGH = 2;
public static final int OFF = -1;
private int status;
public Light() {
status = OFF;
}
public void setLow() {
System.out.println("Light is be changed to low");
status = LOW;
}
public void setMid() {
System.out.println("Light is be changed to mid");
status = MID;
}
public void setHigh() {
System.out.println("Light is be changed to high");
status = HIGH;
}
public void turnOff() {
System.out.println("Light is turned off");
status = OFF;
}
public int getStatus() {
return status;
}
}
public class User {
private Command[] commands;
private Stack<Command> s;
public User() {
s = new Stack<Command>();
}
public void setCommand(Command[] com) {
this.commands = com;
}
public void turnOnLow() {
commands[0].execute();
s.push(commands[0]);
}
public void turnOnMid() {
commands[1].execute();
s.push(commands[1]);
}
public void turnOnHigh() {
commands[2].execute();
s.push(commands[2]);
}
public void turnOff() {
commands[3].execute();
s.push(commands[3]);
}
public void undo() {
if (!s.isEmpty()) {
s.pop().undo();
}
}
}
public class LightHighCommand implements Command {
private Light light;
private int preStatus;
public LightHighCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
preStatus = light.getStatus();
light.setHigh();
}
@Override
public void undo() {
if (preStatus == Light.LOW) {
light.setLow();
} else if (preStatus == Light.MID) {
light.setMid();
} else if (preStatus == Light.HIGH) {
light.setHigh();
} else if (preStatus == Light.OFF) {
light.turnOff();
}
}
}
其他几个命令类似
public class PatternDemo {
public static void main(String[] args) {
User user = new User();
Light light = new Light();
LightLowCommand lowCommand = new LightLowCommand(light);
LightMidCommand midCommand = new LightMidCommand(light);
LightHighCommand highCommand = new LightHighCommand(light);
LightTrunOffCommand turnOffCommand = new LightTrunOffCommand(light);
Command[] commands = new Command[] {lowCommand, midCommand, highCommand, turnOffCommand};
user.setCommand(commands);
user.turnOnLow();
user.turnOnMid();
user.turnOnHigh();
user.turnOff();
user.undo();
user.undo();
user.undo();
user.undo();
user.undo();
}
}