备忘录模式

8.1 模式动机

备忘录模式用于保存程序内部状态到外部,又不希望暴露内部状态的情形。

程序内部状态使用窄接口船体给外部进行存储,从而不暴露程序实现细节。

备忘录模式同时可以离线保存内部状态,如保存到数据库,文件等。

8.2 Go语言实现

memento.go

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

memento_test.go

  1. package memento
  2. func ExampleGame() {
  3. game := &Game{
  4. hp: 10,
  5. mp: 10,
  6. }
  7. game.Status()
  8. progress := game.Save()
  9. game.Play(-2, -3)
  10. game.Status()
  11. game.Load(progress)
  12. game.Status()
  13. // Output:
  14. // Current HP:10, MP:10
  15. // Current HP:7, MP:8
  16. // Current HP:10, MP:10
  17. }