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小码哥21 分钟前
大模型成本怎么降,5 个动作先做前两个
java·前端·spring
PHP是世界上最好的语言33 分钟前
ComPDF预览本地正常,部署后白屏:检查资源、路径和许可
前端
kiros_wang34 分钟前
项目分包方案:模块拆分、跨模块组件与方法引用规范
前端
PedroQue9936 分钟前
unix-utils v0.2.0 发布:modal 全端统一,自绘窗口解决输入框难题
前端·uni-app
Csvn37 分钟前
网络优化
前端
代码猎人41 分钟前
前端怎么跟进生态新技术
前端
海阳皓辰网络科技有限公司41 分钟前
Vue3 冷库货位选择器:三级联动、扫码带出与批次混放校验
前端·vue.js
__sjfzllv___43 分钟前
在职前端Leader学习/转行 AI Agent -DAY81
前端
女生也可以敲代码44 分钟前
div上有红色下划线报错:JSX 元素隐式具有类型 “any“,因为不存在接口 “JSX.IntrinsicElements“。ts(7026)
前端
申君健24864182772021 小时前
ArkTS 速成指南(写给有 TypeScript / 前端经验的开发者)
前端