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')
相关推荐
Highcharts.js3 分钟前
数学函数双曲线音频图表(y=1/x 双曲线)|图表代码示例
前端·react.js·实时音视频·highcharts·音频图表·双曲线图表
放下华子我只抽RuiKe58 分钟前
React 从入门到生产(一):JSX 与组件思维
前端·javascript·人工智能·pytorch·深度学习·react.js·前端框架
冴羽yayujs32 分钟前
JavaScript 9 个先有库再有 API 的故事
开发语言·javascript·ecmascript
油丶酸萝卜别吃1 小时前
JavaScript 深度合并函数 deepMerge 实现指南(附完整测试用例)
开发语言·javascript·测试用例
问心无愧05131 小时前
ctf show web 入门152
前端·笔记
kyriewen1 小时前
Copilot下个月按Token收钱,我算了一笔账:重度用户一年要多花3000块
前端·javascript·openai
还有多久拿退休金1 小时前
dnd-kit 碰撞检测算法:你的订单为什么自己"跑"到了 1 号?
前端
qq_316837751 小时前
npm run tauri build Downloading下载超时
前端·npm·node.js
w_t_y_y1 小时前
VUE3(二)VUE2和VUE3区别
前端·javascript·vue.js
T-shmily1 小时前
使用svg图标
前端·css