概念
- 随时记录一个对象的状态变化
- 随时可以恢复之前的某个状态(如撤销功能)
- 未找到JS中经典应用,除了一些工具(如编辑器)
演示
class Memento {
constructor(content) {
this.content = content
}
getContent() {
return this.content
}
}
class CareTeker {
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())
设计原则验证