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')
相关推荐
IT_陈寒7 分钟前
用了Proxy才发现以前的JavaScript白写了
前端·人工智能·后端
爱丶不疚40 分钟前
Eval: Agent 说的 Eval 是什么?从单测、TDD 到 Sentry 聊起
前端·ai编程·vibecoding
求道於盲43 分钟前
python中的类型标注
前端
计算机魔术师1 小时前
从硅谷测试到全球铺开,ChatGPT广告的10亿美元秘密
前端
专业抄代码选手2 小时前
08|Fiber 上的 `useState`:状态终于属于具体组件
前端·javascript·react.js
默_笙2 小时前
😭 Vibe Coding 翻车实录:AI 编程为什么必须先写"剧本"
前端·javascript
LEE2 小时前
原来 Claude Code 最厉害的工具,一行代码都不写
前端·后端
parade岁月2 小时前
为了给表格加虚拟滚动而选了 vxe-table?也可以考虑下这个
前端·vue.js
打呵欠的猫2 小时前
一个 Hook 让 AI 每次写文件前自动检查编码规范,违规代码再也提交不进来
前端·ai编程·代码规范
恋猫de小郭2 小时前
Android 17 + OkHttp 5.5.0 ,全新 ECH 下你的 HTTPS 域名可以请求时被安全隐藏
android·前端·flutter