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')
相关推荐
reembarkation7 小时前
使用pdfjs-dist 预览pdf,并添加文本层的实现
前端·javascript·pdf
reembarkation7 小时前
vue-pdf 实现blob数据的预览
javascript·vue.js·pdf
李明卫杭州7 小时前
JavaScript中的dispatchEvent方法详解
javascript
KenXu7 小时前
F2C-PTD工具将需求快速转换为代码实践
前端
给月亮点灯|7 小时前
Vue3基础知识-setup()、ref()和reactive()
前端·javascript·vue.js
芜青7 小时前
【Vue2手录12】单文件组件SFC
前端·javascript·vue.js
冷冷的菜哥7 小时前
react实现无缝轮播组件
前端·react.js·typescript·前端框架·无缝轮播
hrrrrb7 小时前
【Python】字符串
java·前端·python
阿笑带你学前端8 小时前
Supabase云同步架构:Flutter应用的数据同步策略
前端
Martin-Luo8 小时前
Vue3 通过json配置生成查询表单
javascript·vue.js·json