Skip to content

Commit b054c8d

Browse files
committed
add memento
1 parent 98efd46 commit b054c8d

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed

17_memento/README.md

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# 备忘录模式
2+
3+
备忘录模式用于保存程序内部状态到外部,又不希望暴露内部状态的情形。
4+
5+
程序内部状态使用窄接口船体给外部进行存储,从而不暴露程序实现细节。
6+
7+
备忘录模式同时可以离线保存内部状态,如保存到数据库,文件等。

17_memento/memento.go

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package memento
2+
3+
import "fmt"
4+
5+
type Memento interface{}
6+
7+
type Game struct {
8+
hp, mp int
9+
}
10+
11+
type gameMemento struct {
12+
hp, mp int
13+
}
14+
15+
func (g *Game) Play(mpDelta, hpDelta int) {
16+
g.mp += mpDelta
17+
g.hp += hpDelta
18+
}
19+
20+
func (g *Game) Save() Memento {
21+
return &gameMemento{
22+
hp: g.hp,
23+
mp: g.mp,
24+
}
25+
}
26+
27+
func (g *Game) Load(m Memento) {
28+
gm := m.(*gameMemento)
29+
g.mp = gm.mp
30+
g.hp = gm.hp
31+
}
32+
33+
func (g *Game) Status() {
34+
fmt.Printf("Current HP:%d, MP:%d\n", g.hp, g.mp)
35+
}

17_memento/memento_test.go

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package memento
2+
3+
func ExampleGame() {
4+
game := &Game{
5+
hp: 10,
6+
mp: 10,
7+
}
8+
9+
game.Status()
10+
progress := game.Save()
11+
12+
game.Play(-2, -3)
13+
game.Status()
14+
15+
game.Load(progress)
16+
game.Status()
17+
18+
// Output:
19+
// Current HP:10, MP:10
20+
// Current HP:7, MP:8
21+
// Current HP:10, MP:10
22+
}

0 commit comments

Comments
 (0)