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')
相关推荐
HuangYongbiao7 小时前
Rspack Loader 架构原理:从 Loader Runner 到 Rust Loader Pipeline
前端·架构
hen3y7 小时前
基于 jscodeshift 构建高效 Codemod 工具指南
前端·javascript
烛阴7 小时前
代码的灵魂:C# 方法全景解析(万字长文,建议收藏)
前端·c#
龙国浪子7 小时前
🎯 小说笔记编辑中的段落拖拽移动:基于 ProseMirror 的交互式重排技术
前端·electron
iFlow_AI7 小时前
iFlow CLI快速搭建Flutter应用记录
开发语言·前端·人工智能·flutter·ai·iflow·iflow cli
兔子零10247 小时前
前端开发实战笔记:为什么从 Axios 到 TanStack Query,是工程化演进的必然?
前端
面向div编程7 小时前
Vite的知识点
前端
疯狂踩坑人7 小时前
【前端工程化】一文看懂现代Monorepo(npm)工程
前端·npm·前端工程化
JarvanMo7 小时前
Flutter:如何更改默认字体
前端
默海笑7 小时前
VUE后台管理系统:定制化、高可用前台样式处理方案
前端·javascript·vue.js