备忘录模式

备忘录模式

备忘录

package memento

type memento struct {
hp int
mp int
}

func NewMemento(hp,mp int) *memento {
return &memento{
hp:hp,
mp:mp,
}
}

游戏角色

package memento

type role struct {
hp int
mp int
}

func NewRole() *role {
return &role{
hp:100,
mp:100,
}
}

func (r *role)Save() *memento {
return NewMemento(r.hp,r.mp)
}

func (r *role)Fight() {
r.hp -= 10
r.mp -= 10
}

func (r *role)Load(mt *memento) {
r.hp = mt.hp
r.mp = mt.mp
}

func (r *role)Display() {
fmt.Printf("hp:%d,mp:%d\n",r.hp,r.mp)
}

备忘录管理者

当多个备忘录时,可以用栈来管理,这里省略

测试文件

package memento

func TestMemento(t testing.T) {
r := NewRole()
r.Display()
me := r.Save()
r.Fight()
r.Display()
r.Load(me)
r.Display()
}

posted @ 2022-10-14 15:06  理科土拨鼠  阅读(27)  评论(0)    收藏  举报