一、概念
备忘录模式(Memento Pattern):也叫快照(Snapshot)模式,在不违背封装原则的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,以便之后恢复对象为先前的状态。通俗点就是用于保存某个对象的状态,以便在适当的时候恢复对象。简单的应用比如:游戏存档、浏览器中的后退、word中的撤销。
二、实现
这里举一个word
中添加撤销的例子。
1、Word
public class Word {StringBuilder content = new StringBuilder();public String getContent() {return content.toString();}public void append(String input) {content.append(input);}public WordMemento createWordMemento() {return new WordMemento(content.toString());}public void restoreWordMemento(WordMemento wordMemento) {content.replace(0, content.length(), wordMemento.getContent());}
}
2、WordMemento
表示word
操作过程状态,该数据一旦创建不能留修改入口。
public class WordMemento {private String content;public WordMemento(String content) {this.content = content;}public String getContent() {return content;}
}
3、WordMementoHolder
状态控制类
public class WordMementoHolder {private Stack<WordMemento> stack = new Stack<>();private static class WordMementoHolderSingleton {private static final WordMementoHolder INSTANCE = new WordMementoHolder();}public static WordMementoHolder getInstance() {return WordMementoHolderSingleton.INSTANCE;}public void pushWordMemento(WordMemento wordMemento) {stack.push(wordMemento);}public WordMemento popWordMemento() {return stack.pop();}public WordMemento getStackTopMemento(){return stack.peek();}
}
4、测试类
public class Client {public static void main(String[] args) {WordMementoHolder wordMementoHolder = WordMementoHolder.getInstance();Word word = new Word();String str1 = "hello";String str2 = "123";String str3 = "java";//添加第一个word.append(str1);wordMementoHolder.pushWordMemento(word.createWordMemento());System.out.println(word.getContent());//添加第二个word.append(str2);wordMementoHolder.pushWordMemento(word.createWordMemento());System.out.println(word.getContent());//添加第三个word.append(str3);wordMementoHolder.pushWordMemento(word.createWordMemento());System.out.println(word.getContent());//撤销第三个wordMementoHolder.popWordMemento();word.restoreWordMemento(wordMementoHolder.getStackTopMemento());System.out.println(word.getContent());}
}
5、运行结果