5 撤销操作的实现
|
|
图5
-
//加法类:请求接收者
-
class
Adder { -
private int num= 0;//定义初始值为0 -
-
//加法操作,每次将传入的值与num作加法运算,再将结果返回 -
public int add( intvalue) { -
num += value; -
return num; -
} - }
-
-
//抽象命令类
-
abstract
class AbstractCommand { -
public abstract int execute( intvalue); //声明命令执行方法execute() -
public abstract int undo(); //声明撤销方法undo() - }
-
-
//具体命令类
-
class
ConcreteCommand extendsAbstractCommand { -
private Adder newadder = Adder(); -
private int value; -
-
//实现抽象命令类中声明的execute()方法,调用加法类的加法操作 -
public
int execute( intvalue) { -
this.value=value; -
return adder.add(value); -
} -
-
//实现抽象命令类中声明的undo()方法,通过加一个相反数来实现加法的逆向操作 -
public int undo() { -
return adder.add(-value); -
} - }
-
-
//计算器界面类:请求发送者
-
class
CalculatorForm { -
private AbstractCommand command; -
-
public void setCommand(AbstractCommand command) { -
this.command = command; -
} -
-
//调用命令对象的execute()方法执行运算 -
public void compute( intvalue) { -
int i = command.execute(value); -
System.out.println("执行运算,运算结果为:" + i); -
} -
-
//调用命令对象的undo()方法执行撤销 -
public void undo() { -
int i = command.undo(); -
System.out.println("执行撤销,运算结果为:" + i); -
} - }
-
class
Client { -
public static void main(String args[]) { -
CalculatorForm form = new CalculatorForm(); -
AbstractCommand command; -
command = new ConcreteCommand(); -
form.setCommand(command); //向发送者注入命令对象 -
-
form.compute(10); -
form.compute(5); -
form.compute(10); -
form.undo(); -
} - }
执行运算,运算结果为:10 执行运算,运算结果为:15 执行运算,运算结果为:25 执行撤销,运算结果为:15 |
|
|
【作者:刘伟