备忘录模式——实现撤销操作
思路

IMG_20200307_152700.png

image.png
Editor
/*
带撤销功能的文字编辑器——编辑器类
*/
public class Editor {
//保存当前内容
private String content;
//当使用这个方法时,编辑器会以一个编辑器状态对象保存现在的状态,并返回它
public EditorState createState(){
return new EditorState(content);
}
public void restore(EditorState state){
content = state.getContent();
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
/*
//1.(撤销一次)添加一个新的字段,叫prevContent,每次我们要修改content的值的时候,我们先把当
前的值保存到prevContent,然后再修改content private String prevContent;
//2.(撤销多次)List类型——不易扩展
private List prevContents;
*/
EditorState
public class EditorState {
private final String content;
public EditorState(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
History
import java.util.ArrayList;
import java.util.List;
public class History {
//这个尖括号中表示我们想要保存的数据类型
private List<EditorState> states = new ArrayList<>();
//存入
public void push(EditorState state){
states.add(state);
}
//取出
public EditorState pop(){
var lastIndex = states.size() - 1;
var lastState = states.get(lastIndex);
states.remove(lastState);
return lastState;
}
}
Main
public class Main {
public static void main(String[] args) {
var editor = new Editor();
var history = new History();
editor.setContent("a");
history.push(editor.createState());
editor.setContent("b");
history.push(editor.createState());
editor.setContent("c");
editor.restore(history.pop());
editor.restore(history.pop());
String content = editor.getContent();
System.out.println(content);
}
}