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')
相关推荐
布列瑟农的星空6 小时前
Playwright使用体验
前端·单元测试
卤代烃7 小时前
🦾 可为与不可为:CDP 视角下的 Browser 控制边界
前端·人工智能·浏览器
_XU7 小时前
AI工具如何重塑我的开发日常
前端·人工智能·深度学习
C_心欲无痕7 小时前
vue3 - defineExpose暴露给父组件属性和方法
前端·javascript·vue.js·vue3
鹿人戛7 小时前
HarmonyOS应用开发:相机预览花屏问题解决案例
android·前端·harmonyos
萌萌哒草头将军8 小时前
绿联云 NAS 安装 AudioDock 详细教程
前端·docker·容器
贺今宵8 小时前
安装better-sqlite3报错electron-vite
javascript·sql·sqlite·sqlite3
GIS之路8 小时前
GIS 数据转换:使用 GDAL 将 GeoJSON 转换为 Shp 数据
前端
2501_944446008 小时前
Flutter&OpenHarmony文件夹管理功能实现
android·javascript·flutter
爱学习的小可爱卢9 小时前
JavaEE进阶——Spring核心设计模式深度剖析
java·spring·设计模式