专业编程教程与实战项目分享平台

网站首页 > 技术文章 正文

高级前端必会设计模式之备忘录模式

ins518 2024-09-11 09:28:38 技术文章 20 ℃ 0 评论

前端JavaScript设计模式-备忘录模式:

备忘录模式指可以随时记录一个对象的状态变化,并且可以随时恢复之前的某个状态,此模式通常在文本编辑器中应用

Bash
// 备忘状态
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('输入内容一')
editor.setContent('输入内容二')
// 存储备忘录
careTaker.add(editor.saveContentToMemento())
editor.setContent('输入内容三')
// 存储备忘录
careTaker.add(editor.saveContentToMemento())
editor.setContent('输入内容四')

console.log(editor.getContent())
// 撤销
editor.getContentFromMemento(careTaker.get(1))
console.log(editor.getContent())
//撤销
editor.getContentFromMemento(careTaker.get(0))
console.log(editor.getContent())

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表