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')
相关推荐
程序猿_极客18 分钟前
【期末网页设计作业】HTML+CSS+JS 旅行社网站、旅游主题设计与实现(附源码)
javascript·css·html·课程设计·期末网页设计
百***359423 分钟前
如何在树莓派部署Nginx并实现无公网ip远程访问内网制作的web网站
前端·tcp/ip·nginx
用户2832096793726 分钟前
为什么我的页面布局总是乱糟糟?可能是浮动和BFC在作怪!
javascript
花果山总钻风29 分钟前
Chrome 插件框架 Plasmo 基本使用示例
前端·chrome
资讯第一线31 分钟前
《Chrome》 [142.0.7444.60][绿色便携版] 下载
前端·chrome
会篮球的程序猿43 分钟前
原生表格文本过长展示问题,参考layui长文本,点击出现文本域
前端·javascript·layui
top_designer43 分钟前
Firefly 样式参考:AI 驱动的 UI 资产“无限”生成
前端·人工智能·ui·aigc·ux·设计师
蜗牛前端1 小时前
使用 Trae AI 开发完整的开源 npm 包:snail-git-add
前端
哆啦A梦15881 小时前
48 我的地址页面布局
javascript·vue.js·node.js
Dontla1 小时前
React useMemo(当依赖项未变化,重复渲染时直接返回上一次缓存计算结果,而非重新执行计算)
前端·react.js·缓存