-
Notifications
You must be signed in to change notification settings - Fork 46
/
main.go
92 lines (77 loc) · 1.6 KB
/
main.go
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// 备忘录模式 memento pattern
// 在不影响原结构封装的情况下,能够暂时保存一个结构的状态,并能够恢复
// 这里是一个游戏存档的例子,尝试保存玩家当前位置,并在读档的时候恢复
package main
import (
"container/list"
"log"
)
// originator
type Player struct {
// 需要记录的数据可以考虑单独封装
// type Pos struct{X,Y int}
X,Y int
// other info
Name string
}
func (p *Player)MoveTo(x,y int){
p.X = x
p.Y = y
}
func (p Player)Save()PlayerMemento{
return PlayerMemento{
X:p.X,
Y:p.Y,
}
}
func (p *Player)Restore(m PlayerMemento){
p.X = m.X
p.Y = m.Y
}
// memento
type PlayerMemento struct {
X,Y int
}
// caretaker
type PlayerCareTaker struct {
MementoList *list.List
}
func (ct *PlayerCareTaker)AddMemento(memento PlayerMemento){
ct.MementoList.PushFront(memento)
}
func (ct *PlayerCareTaker)RemoveLast()PlayerMemento{
ele := ct.MementoList.Front()
val := ct.MementoList.Remove(ele)
if memento ,ok := val.(PlayerMemento);ok{
return memento
}else{
return PlayerMemento{}
}
}
func main(){
ct := &PlayerCareTaker{list.New()}
icg := &Player{
X:114,
Y:514,
Name:"icg",
}
ct.AddMemento(icg.Save())
log.Println(icg.X ,icg.Y)
icg.MoveTo(810 ,19)
log.Println(icg.X ,icg.Y)
ct.AddMemento(icg.Save())
icg.MoveTo(0 ,0)
log.Println(icg.X ,icg.Y)
icg.Restore(ct.RemoveLast())
log.Println(icg.X ,icg.Y)
icg.Restore(ct.RemoveLast())
log.Println(icg.X ,icg.Y)
/*
output:
2019/05/02 18:18:03 114 514
2019/05/02 18:18:03 810 19
2019/05/02 18:18:03 0 0
2019/05/02 18:18:03 810 19
2019/05/02 18:18:03 114 514
*/
}