Day02

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

思路

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);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 回顾: 1.什么是GNU? GNU: GNU是一个组织,组织里面有许多免费且开源的项目,用户可以自由下载,自由分发...
    一条小强强OvO阅读 283评论 2 4
  • 1.什么是GNU? GNU:不是unix copyleft opensource free gpl 通用许可协议,...
    wiapr阅读 151评论 0 0
  • 一、VMware快照如何建立? 此项过于简单,直接省略。 二、什么是Bash shell? 终端;命令解释器、将用...
    风铃科技阅读 266评论 0 0
  • fantastic语歌阅读 446评论 7 11
  • 高考完的夏天,北笙的爸爸突发脑梗塞进医院,家里的顶梁柱一下子倒了,让这个家庭的经济情况一下子捉襟见肘,自从爸爸生病...
    180斤的考拉阅读 692评论 6 8

友情链接更多精彩内容