Skip to content

Latest commit

 

History

History
73 lines (65 loc) · 1.68 KB

21-备忘录模式.md

File metadata and controls

73 lines (65 loc) · 1.68 KB

备忘录模式

概念

  • 随时记录一个对象的状态变化
  • 随时可以恢复之前的某个状态(如撤销功能)
  • 未找到JS中经典应用,除了一些工具(如编辑器)

代码演示

// 备忘类
class Memento {
    constructor(content) {
        this.content = content
    }
    getContent() {
        return this.content
    }
}

// 备忘列表
class CareTaker {
    constructor() {
        this.list = []
    }
    add(memento) {
        this.list.push(memento)
    }
    get(index) {
        return this.list[index]
    }
}

// 编辑器
class Editor {
    constructor() {
        this.content = null
    }
    setContent(content) {
        this.content = content
    }
    getContent() {
        return this.content
    }
    // 保存到备忘
    saveContentToMemento() {
        return new Memento(this.content)
    }
    getContentFromMemento(memento) {
        this.content = memento.getContent()
    }
}

// 测试
let editor = new Editor()
let careTaker = new CareTaker()

editor.setContent('111')
editor.setContent('222')
careTaker.add(editor.saveContentToMemento()) // 将当前内容备份
editor.setContent('333')
careTaker.add(editor.saveContentToMemento()) // 将当前内容备份
editor.setContent('444')

console.log(editor.getContent()) // 打印当前内容
editor.getContentFromMemento(careTaker.get(1)) // 撤销
console.log(editor.getContent()) // 打印当前内容
editor.getContentFromMemento(careTaker.get(0)) // 撤销
console.log(editor.getContent()) // 打印当前内容

设计原则验证

  • 状态对象与使用者分开,解耦
  • 符合开放封闭原则