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')
相关推荐
兔子零10241 分钟前
架构师最危险的能力:用正确的技术,做出错误的架构决策
前端·javascript·后端
Bug收容所21 分钟前
Vue+js Day2
前端·javascript·vue.js
掘金酱1 小时前
带着作品来,坐下来聊|掘金 X-lab · Coffee Talk 邀请你来见一面
前端·javascript·后端
CoovallyAIHub2 小时前
用 AI 做 PPT 被辞退,法院判公司赔:员工贴进对话框的数据,到底谁负责?
前端·agent
fruge2 小时前
SSH、RDP、VNC不必各开一个客户端:Next Terminal用Web入口统一管理远程资产和会话记录
运维·前端·ssh
geovindu2 小时前
rust: Mediator Pattern
开发语言·后端·设计模式·rust·中介者模式·行为模式
honkun62 小时前
vue 下拉树组件 vxe-table-select 实现分页多选
前端·javascript·vue.js
大熊程序猿3 小时前
用 ASP.NET Core + SignalR 做一个带实时对战房间的打字练习平台
javascript
OpsEye3 小时前
大量无效 Token 消耗,是很多企业被忽略的隐形成本
javascript·ai编程
用户621007587023 小时前
Web BIM 开发实践:如何将构件选择、属性查询接入业务系统?
前端