js设计模式:备忘录模式

作用:

封装的对象可以在对象触发行为时进行状态的记录与保存

也可以进行状态的回退,恢复之前的状态

示例:

javascript 复制代码
        class Editor{
            constructor(){
                 this.allText = ''
            }
            edit(text){
              this.allText += text
            }
            saveNow(){
                return new EditorText(this.allText)
            }
            backspacing(editorText){
                 this.allText = editorText.getText()
                 console.log(this.allText,'???')
            }
        }

        class EditorText{
            constructor(text){
                this.text = text
            }
            getText(){
                return this.text
            }
        }

        class History{
            constructor(){
                this.textNodeList = []
            }
            add(text){
              this.textNodeList.push(text)
            }
            delete(){
                this.textNodeList.pop()
                return this.textNodeList[this.textNodeList.length-1]
            }
        }

        const editor = new Editor()
        const history = new History()

        editor.edit('两个黄鹂鸣翠柳,')
        history.add(editor.saveNow())
        console.log(editor,'当前文本1')
        console.log(history,'历史记录1')


        editor.edit('一行白鹭上西天。')
        history.add(editor.saveNow())
        console.log(editor,'当前文本2')
        console.log(history,'历史记录2')

        //写的不对,撤回一下
        editor.backspacing(history.delete())
        console.log(editor,'当前文本3')
        console.log(history,'历史记录3')

        editor.edit('一行白鹭上青天。')
        history.add(editor.saveNow())
        console.log(editor,'当前文本4')
        console.log(history,'历史记录4')
相关推荐
Java展博6 小时前
[前端够用就好] 跨域报错时,浏览器到底在拦谁
前端·状态模式
用户112936112196 小时前
npm 都提示成功了,node_modules 为什么还占着 370M?
linux·前端·后端
掘金安东尼7 小时前
Agent Harness 也有 benchmark:评分榜与评测工作台现状
前端·agent
digger_4197 小时前
从零理解 Electron:主进程、渲染进程、preload 与 IPC 实战
前端·electron
去伪存真8 小时前
别让你的 RAG 平台“花五份钱、答一份结巴的题”:幂等性架构的自我修养
前端·agent
snow@li9 小时前
前端:导入EXCEL并解析文件内容,demo
前端·javascript·vue.js
补码缩写9 小时前
压缩PNG不损失透明:只量化RGB、alpha原样留的减色流程
前端
TDengine (老段)10 小时前
TDengine IDMP 知识库与知识图谱
大数据·前端·物联网·知识图谱·时序数据库·tdengine·涛思数据
饮水桶_T11 小时前
Java调用大语言模型 笔记
笔记·设计模式·电脑·ai编程
goehou11 小时前
PNG 转 WebP 不一定变小,我量了三类图
前端·性能优化·webp·sharp