命令模式
某系统需要提供一个命令集合(注:可以使用链表,栈等集合对象实现),用于存储一系列命令对象,并通过该命令集合实现多次undo()和redo()操作,可以使用加法运算来模拟实现。
package com; //抽象命令类 public abstract class AbstractCommand { public abstract int execute(int value); public abstract int undo(); public abstract int redo(); }
package com; //请求接受者 public class Adder { private int num=0; public int add(int value){ num+=value; return num; } }
package com; //具体命令类 public class ConcreteCommand extends AbstractCommand{ private int[] a=new int[50]; private int i=0; private Adder adder=new Adder(); private int value; @Override public int execute(int value) { this.value = value; a[i] = value; i++; return adder.add(value); } @Override public int undo() { if(i-->=0) { i--; return adder.add(-a[i]);} else { System.out.println("不能撤销了o~"); return adder.add(0); } } @Override public int redo() { i++; return adder.add(a[i-1]); } }
package com; public class CalculatorForm { private AbstractCommand command; public void setCommand(AbstractCommand command){ this.command=command; } public void computer(int value){ int i=command.execute(value); System.out.println("执行运算,运算结果为:"+i); } public void undo(){ int i=command.undo(); System.out.println("执行撤销,运算结果为:"+i); } public void redo(){ int i=command.redo(); System.out.println("取消撤销,运算结果为:"+i); } }
客户端
package com; public class Client { public static void main(String[] args) { CalculatorForm form=new CalculatorForm(); AbstractCommand command; command=new ConcreteCommand();//重构这行代码,可以更换具体命令类 form.setCommand(command); form.computer(10); form.computer(5); form.undo(); form.undo(); form.redo(); form.computer(3); } }
运行结果