/**
* 加法器,计算求和。
*
* @author zhangfly
*
*/
public class Adder {
private int sum = 0;
public int add(int value) {
System.out.print("加法器计算:" + sum + "+(" + value + ")=");
sum = sum + value;
System.out.println(sum);
return sum;
}
}
public abstract class Command {
public abstract int execute(int value);// 在原先和基础上再加上一个value的值。
public abstract int undo(); // 撤销。
}
public class ConcreteCommand extends Command {
private Adder adder = new Adder();
private int value = 0;
@Override
public int execute(int value) {
this.value = value;
return adder.add(value);
}
@Override
public int undo() {
return adder.add(-value);
}
}
public class Calculator {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
// 执行运算.
public void compute(int value) {
int v = command.execute(value);
System.out.println("运算结果:" + v);
}
// 调用命令对象的undo()方法执行撤销
public void undo() {
int v = command.undo();
System.out.println("撤销,此时结果:" + v);
}
}
public class Test {
public Test() {
Calculator calculator = new Calculator();
Command command = new ConcreteCommand();
calculator.setCommand(command);
calculator.compute(1);
calculator.compute(2);
calculator.compute(3);
calculator.compute(4);
calculator.compute(5);
calculator.undo();
}
public static void main(String[] args) {
new Test();
}
}
输出:
加法器计算:0+(1)=1
运算结果:1
加法器计算:1+(2)=3
运算结果:3
加法器计算:3+(3)=6
运算结果:6
加法器计算:6+(4)=10
运算结果:10
加法器计算:10+(5)=15
运算结果:15
加法器计算:15+(-5)=10
撤销,此时结果:10