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')
相关推荐
繁花郁晴8 分钟前
【转录字幕】自用备忘录
备忘录模式
程序员爱钓鱼24 分钟前
配置 GoLand 与 VS Code 开发环境
前端·后端·go
程序员爱钓鱼32 分钟前
Rust Vec 动态数组详解:创建、增删、遍历与排序
前端·后端·rust
谢栋_1 小时前
设计模式从入门到精通之(七)责任链模式
java·设计模式·责任链模式
LaughingZhu1 小时前
Product Hunt 每日热榜 | 2026-07-23
前端·神经网络·react.js·搜索引擎·前端框架
To_OC1 小时前
拼路径读文件总踩坑?我把 Node 的 path 和 fs 彻彻底底捋了一遍
javascript·后端·node.js
自然 醒1 小时前
记录We码开发者工具的一个bug
前端·javascript·bug
葡萄城技术团队1 小时前
HTML元素单元格:用自定义 CellType 扩展 SpreadJS 的显示能力
前端·javascript·html
不好听6131 小时前
Fragment:React 的 `<></>` 和原生的 DocumentFragment,同名不同命
前端·react.js·dom
不好听6131 小时前
useState 完全解析:初始化、异步更新、以及为什么传函数能解决闭包问题
前端·react.js