package test;
public abstract class AbstractCommand {
public abstract int execute(int value);
public abstract int undo();
}
package test;
public class Adder {
private int num=0;
public int add(int value) {
num += value;
return num;
}
}
package test;
public class CalculatorForm {
private AbstractCommand command;
public void setCommand(AbstractCommand command) {
this.command = command;
}
public void compute(int value) {
int i = command.execute(value);
System.out.println("执行结果为" + i);
}
public void undo() {
int i = command.undo();
System.out.println("撤销:" + i);
}
}
package test;
public class Client {
public static void main(String args[]) {
CalculatorForm form = new CalculatorForm();
AbstractCommand command;
command = new ConcreteCommand();
form.setCommand(command);
form.compute(3);
form.compute(4);
form.compute(5);
form.undo();
form.undo();
form.undo();
}
}
package test;
class ConcreteCommand extends AbstractCommand {
private Adder adder = new Adder();
private int value;
public int execute(int value) {
this.value=value;
return adder.add(value);
}
public int undo() {
return adder.add(-value);
}
}