备忘录
public class Invoker { List<String> backupLib = new ArrayList<>(List.of(""));//新建空白文档 private TextEditor receiver; int index = 0; public Invoker(TextEditor receiver) { this.receiver = receiver; } public Invoker invoke(Command c) { c.execute(); if (!(c instanceof CopyCommand)) {//copy命令不备份数据 if (index>0&&index < backupLib.size()-1) {//覆盖版本范围,从1到最新版本-1 index++; backupLib.set(index, receiver.getState()); } else { backupLib.add(receiver.getState()); index++; } } return this; } public Invoker undo() { if (index > 0) { index--; restore(index); } return this; } public Invoker redo() { if (index < backupLib.size() - 1) { index++; restore(index); } return this; } public void restore(int index) { String restore = backupLib.get(index); receiver.setState(restore); } }
//public class TextEditor下面添加 //Memonto恢复备份 public void setState(String state) { buffer.delete(0, buffer.length());//buffer清空方法,免创建对象 buffer.append(state); }
//测试方法 public static void main(String[] args) { TextEditor editor = new TextEditor(); Invoker inv=new Invoker(editor); // editor.add("Command pattern in text editor.\n"); Command add=new AddCommand(editor, "Command pattern in text editor.\n"); Command copy = new CopyCommand(editor); // copy.execute(); // editor.add("----\n"); Command add2=new AddCommand(editor, "----\n"); Command paste = new PasteCommand(editor); inv.invoke(add); inv.invoke(copy); inv.invoke(add2); inv.invoke(paste); inv.undo(); inv.invoke(add2); inv.undo(); inv.redo(); // inv.undo(); // inv.invoke(add); // inv.undo(); // inv.redo(); // paste.execute(); System.out.println(editor.getState()); }
Sign in to make a reply
Best of Me
备忘录