java设计模式之备忘录
备忘录模式又叫快照模式,既在不改变原对象的情况下,保存一系列它的快照,可以实现备份、撤销等操作。
InputText就是原对象,SnapShot是他的快照,SnapShotHolder负责保存一系列快照
public class InputText { private StringBuilder text = new StringBuilder(); public Snapshot createSnapshot() { return new Snapshot(text.toString()); } public void append(String input) { text.append(input); } public void restoreSnapshot(Snapshot snapshot) { this.text.replace(0, this.text.length(), snapshot.getText()); } }
public class Snapshot { private String text; public Snapshot(String text) { this.text = text; } public String getText() { return this.text; } }
快照容器类
public class SnapshotHolder { private Stack<Snapshot> snapshots = new Stack<>(); public Snapshot popSnapshot() { return snapshots.pop(); } public void pushSnapshot(Snapshot snapshot){ snapshots.push(snapshot); } }
启动类
public class ApplicationMain { public static void main(String[] args) { InputText inputText = new InputText(); SnapshotHolder snapshotHolder = new SnapshotHolder(); Scanner scanner = new Scanner(System.in); while (scanner.hasNext()){ String input = scanner.next(); if(input.equals(":list")){ System.out.println(inputText.toString()); }else if(input.equals(":undo")){ Snapshot snapshot = snapshotHolder.popSnapshot(); inputText.restoreSnapshot(snapshot); }else{ snapshotHolder.pushSnapshot(inputText.createSnapshot()); inputText.append(input); } } } }
输出:
>hello >:list hello >world >:list helloworld >:undo >:list hello