/** * 行为处理者 */ public class Executor { public void setFontSize() { // do something } public void undoSetFontSize() { // do something } public void setOrder() { // do something } public void undoSetOrder() { // do something } }
/** * 命令抽象类 */ public abstract class Command {
/** * 执行人 */ Executor executor;
public Command(Executor executor) { this.executor = executor; }
/** * 执行该命令 */ void execute();
/** * 撤销时应该做的事 */ void fireUndo(); }
/** * 设置字体大小命令 */ public class SetFontSizeCommand extends Command { public SetFontSizeCommand(Executor executor) { super(executor); }
@Override public void execute() { this.executor.setFontSize(); }
@Override public void fireUndo() { this.executor.undoSetFontSize(); } }
/** * 设置排序命令 */ public class SetOrderCommand extends Command { public SetOrderCommand(Executor executor) { super(executor); }
@Override public void execute() { this.executor.setOrder(); }
@Override public void fireUndo() { this.executor.undoSetOrder(); } }
/** * 操作记录 */ public class OperateRecord { // 命令列表 List<Command> commands = new LinkedList<>();
/** * 增加命令 */ public void addCommand(Command command) { commands.add(command); // 最多撤销20步,超过则去掉最先加入列表的命令 if (commands.size() > 20) { commands.remove(0); } }
/** * 执行命令 */ public void execute() { for (Command com : commands) { com.execute(); } }