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
this.careTaker = new CareTaker()
}
setContent(content) {
this.content = content
}
getContent() {
return this.content
}
save() {
this.careTaker.add(new Memento(this.content))
}
restore(index) {
const memento = this.careTaker.get(index)
return memento && memento.getContent()
}
}
const editor = new Editor()
editor.setContent('今天天气不错')
editor.setContent('我也这么觉得')
editor.save()
editor.setContent('明天天气怎么样')
editor.save()
editor.setContent('好像也还阔以')
console.log(editor.getContent())
console.log(editor.restore(1))
console.log(editor.restore(0))