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')
相关推荐
盈建云系统几秒前
小程序表单提交、input 双向绑定,最简洁写法
前端·小程序·apache
XiYang-DING13 分钟前
【Java EE】Cookie
服务器·前端·java-ee
问心无愧051317 分钟前
CTF show web入门45
android·前端·笔记
廖松洋(Alina)19 分钟前
03主入口页面与导航结构-鸿蒙PC端Electron开发
前端·javascript·华为·electron·开源·harmonyos·鸿蒙
nnsix20 分钟前
设计模式 - 单例模式 笔记
笔记·单例模式·设计模式
廖松洋(Alina)21 分钟前
09词根分解与水印展示-鸿蒙PC端Electron开发
前端·javascript·华为·electron·开源·harmonyos·鸿蒙
matrixmind824 分钟前
sindresorhustype-fest:TypeScript 工具类型集合
前端·javascript·其他·typescript
通往曙光的路上31 分钟前
JUCJUCJUC
java·前端·数据库
Swift社区33 分钟前
鸿蒙 PC vs Web:谁才是未来应用形态?
前端·华为·harmonyos
雪度娃娃34 分钟前
结构型设计模式——外观模式
c++·设计模式·外观模式