详细示例:(遥控开关灯)
package command;
public class Light {
String aa;
public Light(String aa) {
super();
this.aa = aa;
}
public void on() {
System.out.println("开灯..");
}
public void off() {
System.out.println("关灯...");
}
}
package command;
/**
* 命令接口 执行开关方法 撤销方法
* */
public interface Command {
public void execute();
public void undo();
}
package command;
/**
* 开灯
* */
public class LightOnCommand implements Command{
Light light;
public LightOnCommand(Light light){
this.light=light;
}
@Override
public void execute() {
// TODO Auto-generated method stub
light.on();
}
@Override
public void undo() {
// TODO Auto-generated method stub
light.off();
}
}
package command;
/**
* 关灯
* */
public class LightOffCommand implements Command {
Light light;
public LightOffCommand(Light light) {
super();
this.light = light;
}
@Override
public void execute() {
// TODO Auto-generated method stub
light.off();
}
@Override
public void undo() {
// TODO Auto-generated method stub
light.on();
}
}
package command;
/**
* 用于初始化
* */
public class NoCommand implements Command{
@Override
public void execute() {
// TODO Auto-generated method stub
System.out.println("没有");
}
@Override
public void undo() {
// TODO Auto-generated method stub
System.out.println("没有");
}
}
package command;
/**
* 命令的发布者 遥控机(拥有记录操作过的命令的功能)
* */
public class RemoteControlWithUndo {
Command[] onCommands;
Command[] offCommands;
Command undoCommand;
// 初始所有命令为null
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) {
onCommands[slot] = onCommand;
offCommands[slot] = offCommand;
}
// 执行并记录命令
public void onButtonWasPushed(int slot) {
onCommands[slot].execute();
undoCommand = onCommands[slot];
}
public void offButtonWasPushed(int slot) {
offCommands[slot].execute();
undoCommand = offCommands[slot];
}
public void undoButtonWasPushed() {
undoCommand.undo();
}
}
package command;
public class Client {
public static void main(String[] args) {
RemoteControlWithUndo remoteControl = new RemoteControlWithUndo();
Light livingRoomLight = new Light("卧室的灯");
LightOnCommand lightOnCommand = new LightOnCommand(livingRoomLight);
LightOffCommand lightOffCommand = new LightOffCommand(livingRoomLight);
remoteControl.setCommand(0, lightOnCommand, lightOffCommand);
remoteControl.onButtonWasPushed(0);
remoteControl.offButtonWasPushed(0);
System.out.println(remoteControl);
remoteControl.undoButtonWasPushed();
remoteControl.offButtonWasPushed(0);
remoteControl.onButtonWasPushed(0);
System.out.println(remoteControl);
remoteControl.undoButtonWasPushed();
}
}
执行结果:
开灯..
关灯…
command.RemoteControlWithUndo@15db9742
开灯..
关灯…
开灯..
command.RemoteControlWithUndo@15db9742
关灯…