前端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())
本文暂时没有评论,来添加一个吧(●'◡'●)