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')
相关推荐
a努力。3 分钟前
Context-State-Memory三重信息架构揭秘
java·服务器·前端
颜进强24 分钟前
23 · NestJs ModuleRef 模块引用:容器递给你的"取货窗口",四个 API 四种语义
前端·后端·ai编程
码林鼠33 分钟前
dart语言教学
前端
光影少年33 分钟前
如果 React 组件的属性没有传值,它的默认值是什么?
前端·javascript·react.js
风骏时光牛马1 小时前
AI_Coding:智能代码生成与工程实践
前端
颜进强1 小时前
22 · NestJs InjectionScopes 注入作用域:默认单例不是偷懒,是最优——以及何时才该打破
前端·后端·ai编程
liangshanbo12151 小时前
Web Worker 在 AI 前端应用中有什么具体使用场景?
前端·人工智能
拖孩1 小时前
一个全程 AI 写的小程序「厨菜记」,上线 20 天跑通流量主,收入几块钱,开心得不行
前端·后端·微信小程序
颜进强2 小时前
21 · NestJs AsyncProviders 异步提供者:useFactory 返回 Promise 之后,容器发生了什么
前端·后端·ai编程
莪_幻尘2 小时前
Agent 体检:乱编、连锁、失忆,给 Agent 做一次五维体检
前端·人工智能·agent