-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path17-备忘录模式.js
61 lines (52 loc) · 1.1 KB
/
17-备忘录模式.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
保存一个对象的某个状态,以便在适当的时候恢复对象
*/
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 = ''
}
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())