实现命令接口
public interface Command() {
public void execute();
public void undo();
}
实现一个打开点灯的命令
public class LightOnCommand implements Command{
Light light;
public LightOnCommand(Light light) {
this.light=light;
}
public void execute() {
light.on();
}
public void undo() {
light.off();
}
}
实现一个关灯的命令
public class LightOffCommand implements Command{
Light light;
public LightOffCommand(Light light) {
this.light=light;
}
public void execute() {
light.off();
}
public void undo() {
light.on();
}
}
遥控器RemoteControlWithUndo的实现如下:
public class RemoteControlWithUndo{
Command[] onCommands;
Command[] offCommands;
Command undoCommand;
public RemoteControlWithUndo() {
onCommands=new Command[7];
offCommands=new Command[7];
Command noCommand=new NoCommand();
for(int i=0;i<7;i++) {
onCommands[i]=noCommand;
offCommands[i]=noCommand;
}
undoCommand=noCommand;
}
public void setCommand(int slot,Command onCommand,Command offCommand) {
onCommand[slot]=onCommand;
offCommanad[slot]=offCommand;
}
public void onButtonWasPushed(int slot) {
onCommand[slot].execute();
undoCommand=onCommand[slot];
}
public void offButtonWasPushed(int slot) {
offCommand[slot].execute();
undoCommand=offCommand[slot];
}
public void undoCommandWasPushed() {
undoCommand.undo();
}
public String toString() {
//这里是toString代码
}
}
在遥控器中,我们不想每次都检查是否某个插槽都加载了命令。比方说,在这个onButtonWasPushed()方法中,我们可能需要这样的代码:
public void onButtonWasPushed(int slot) {
if(onCommands[slot]!=null) {
onCommands[slot].execute();
}
}
所以,我们要如何避免上述的做法?实现一个不做事情的命令!
public class NoCommand implements Command{
public void execute() {}
}
逐步测试遥控器
public class RemoteLoader{
public static void main(String[] args) {
RemoteControl remoteControl=new RemoteControl();
Light livingRommLight=new Light("Living Room");
Light kitchenLight=new Light("Kitchen");
LightOnCommand livingRoomLightOn=new LightOnCommand(livingRoomLight);
LightOffCommand livingRoomLightOff=new LightOffCommand(livingRoomLight);
LightOnCommand kitchenLightOn=new LightOnCommand(kitchenLight);
LightOffCommand kitchenLightOff=new LightOffCommand(kitchenLight);
remoteControl.setCommand(0,livingRoomLightOn,livingRoomLightOff);
remoteControl.setCommand(1,kitchenLightOn,kitchenLightOff);
System.out.println(remoteControl);
remoteControl.onButtonWasPushed(0);
remoteControl.offButtonWasPushed(0);
remoteControl.undoButtonWashPushed(0);
remoteControl.onButtonWasPushed(1);
remoteControl.offButtonWasPushed(1);
remoteControl.undoButtonWashPushed(1);
}
}