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')
相关推荐
JavaGuide1 小时前
Cloudflare 开源的这套神级安全审计 Skill 太好用了!
前端·后端
孟健2 小时前
用 unslop 拯救 AI 生成网页的塑料感,7 分钟重构落地实测
前端·人工智能·ai编程
feixing_fx3 小时前
JavaScript 是什么:从浏览器脚本到通用编程语言
开发语言·前端·javascript·前端框架·ecmascript
丘山望岳3 小时前
【开发工具】 cluade code常用快捷键
前端
小巫编程室3 小时前
我造了一个 Java 能力包:让 AI 直接调用你的业务代码
java·前端·后端
小y的笔记3 小时前
JavaScript URL 状态同步
前端·javascript
十有八七3 小时前
手搓 Agent(五):学会翻书——RAG,先查资料再回答
前端·人工智能·后端
Swot3 小时前
产品 RAG 知识库与 AI 顾问 设计与实现
前端·后端
htzyl2065 小时前
前端样式-弹窗淡入淡出,为什么你的 `transition` 一直不生效
前端·css·html
Brookty5 小时前
CSS基础知识(二):盒模型、内外边距、外边距折叠与父子元素的布局关系
前端·css