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')
相关推荐
斌味代码20 分钟前
Vue3源码解读(一):响应式系统 reactive/ref 核心原理图解(2026最新版)
前端·javascript·vue.js
yhole27 分钟前
Nginx解决前端跨域问题
运维·前端·nginx
我爱学习好爱好爱28 分钟前
Ansible 常用模块详解:hostname、selinux 、file实战
前端·chrome·ansible
爱丽_28 分钟前
AQS 的 `state`:volatile + CAS 如何撑起原子性与可见性
java·前端·算法
Zik----33 分钟前
Windows安装cuda
前端·ui·xhtml
王杨游戏养站系统33 分钟前
3分钟搭建1个游戏下载站网站教程!SEO站长养站系统!
开发语言·前端·游戏·游戏下载站养站系统·游戏养站系统
是上好佳佳佳呀33 分钟前
【前端(三)】CSS 属性梳理:从字体文本到背景表格
前端·css
gaolei_eit36 分钟前
Vue3信号(Signals)深度解析:重新思考响应式编程的未来
前端
小江的记录本39 分钟前
【端口号】计算机领域常见端口号汇总(完整版)
java·前端·windows·spring boot·后端·sql·spring
Reisentyan41 分钟前
网站开发遇到的一个坑点
前端