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')
相关推荐
deli00700720 分钟前
Markdown 实时预览器:左边写右边看,排版效率翻倍
前端·ai编程
郑州光合科技余经理25 分钟前
海外版外卖系统架构:订单怎么流转、权限怎么分
java·开发语言·前端·系统架构·uni-app·php·ai编程
用户2022522150627 分钟前
字节发布"豆包工作",我从AI PM角度看到的不是功能,是上下文
设计模式
pengyu40 分钟前
【Kotlin 协程修仙录 · 炼虚境 · 初阶】 | 虚空造物:Channel 基础与协程间通信的管道艺术
android·前端·kotlin
提线木偶41 分钟前
CORS 到底谁说了算?一份跨域配置的避坑指南
前端·后端
九九落1 小时前
北京时间校准怎么做?电脑和手机时间不准的排查方法
javascript
AI人工智能+电脑小能手2 小时前
大白话说Java设计模式-37-中介者模式(源码剖析篇)
java·设计模式·线程池·中介者模式·源码分析·executor·applicationeventmulticaster
网安蟹佬霸2 小时前
区块链与智能合约安全实战:从Solidity审计到DeFi漏洞深度剖析
运维·前端·网络·安全·自动化·区块链·智能合约
念何架构之路2 小时前
Gin响应渲染
前端·javascript·gin
invicinble2 小时前
设计网站的底层思路(深刻版本)
前端