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')
相关推荐
小村儿14 分钟前
连载10-Sub-agents 深度解析:从源码理解 Claude Code 的分身术
前端·后端·ai编程
IT_陈寒1 小时前
Vite动态导入把我坑惨了,原来要这样用才对
前端·人工智能·后端
DFT计算杂谈1 小时前
KPROJ编译教程
java·前端·python·算法·conda
觅_1 小时前
前端学习后端的时候 选择一个技术
前端·学习
独泪了无痕1 小时前
CryptoJS:数据安全的JavaScript加密利器
前端·vue.js·node.js
发现一只大呆瓜1 小时前
一文搞懂 Vite 处理CommonJS包、按需编译逻辑及 Rollup 插件兼容规则
前端
Edwardwu1 小时前
写了个y-mxgraph:给 draw.io 接上了 Yjs,顺便解决了部署在 iframe 里的一堆问题
前端·typescript
其实防守也摸鱼2 小时前
软件安全与漏洞--软件安全编码
java·前端·网络·安全·网络安全·web·工具
魔法阵维护师2 小时前
从零开发游戏需要学习的c#模块,第十章(设计模式入门)
学习·游戏·设计模式·c#
用户356302904872 小时前
【设计模式】组合模式——树形结构的统一处理
设计模式