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')
相关推荐
hashiqimiya4 分钟前
html的input的required
java·前端·html
soda_yo15 分钟前
JavaScripe中你所不知道的"变量提升"
javascript
Mapmost19 分钟前
WebGL三维模型标准(二)模型加载常见问题解决方案
前端
Mapmost21 分钟前
Web端三维模型标准(一):单位与比例、多边形优化
前端
www_stdio31 分钟前
JavaScript 执行机制详解:从 V8 引擎到执行上下文
前端·javascript
我命由我1234543 分钟前
HTML - 换行标签的 3 种写法(<br>、<br/>、<br />)
前端·javascript·css·html·css3·html5·js
暮冬十七1 小时前
[特殊字符] Vue3 项目最佳实践:组件命名、目录结构与类型规范指南
前端·前端架构·vue3项目搭建
F_Director1 小时前
简说Vue3 computed原理
前端·vue.js·面试
行走的陀螺仪1 小时前
Flutter 开发环境配置教程
android·前端·flutter·ios
焦糖小布丁1 小时前
代码签名证书如何有效消除Windows系统警告?
前端