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')
相关推荐
笨笨狗吞噬者1 分钟前
【uniapp】解决小程序分包下的json文件编译后生成到主包的问题
前端·uni-app
IT_陈寒14 分钟前
Redis 7个性能优化技巧,让我们的QPS从5k提升到20k+
前端·人工智能·后端
.又是新的一天.37 分钟前
健身房预约系统SSM+Mybatis(五、预约展示)
前端·mybatis
晴殇i1 小时前
DOM嵌套关系全解析:前端必备的4大判断方法与性能优化实战
前端·javascript·面试
字节拾光1 小时前
console.log 打印 DOM 后内容变了?核心原因是 “引用” 而非 “快照”
javascript
似水流年_zyh1 小时前
canvas涂抹,擦除功能组件
前端
胖虎2651 小时前
前端多文件上传核心功能实现:格式支持、批量上传与状态可视化
前端
胖虎2651 小时前
Vue2 项目常用配置合集:多语言、SVG 图标、代码格式化、权限指令 + 主题切换
前端
一键定乾坤1 小时前
npm 源修改
前端
parade岁月1 小时前
Vue 3 响应式陷阱:对象引用丢失导致的数据更新失效
前端