概念
备忘录模式(Memento):在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状态。
需求
利用备忘录模式实现游戏进度备份
UML图
代码
游戏角色类
type GameRole struct {
vit string
atk string
def string
}
func (g *GameRole) SaveState() RoleStateMemento {
return RoleStateMemento{vit: g.vit, atk: g.atk, def: g.def}
}
func (g *GameRole) RecoveryState(memento RoleStateMemento) {
g.vit = memento.vit
g.atk = memento.atk
g.def = memento.def
}
func (g *GameRole) GetInstance() {
g.vit = "100"
g.atk = "100"
g.def = "100"
}
func (g *GameRole) Fight() {
g.vit = "0"
g.atk = "0"
g.def = "0"
}
func (g *GameRole) StateDisplay() {
fmt.Println("角色当前状态:")
fmt.Println("体力:" + g.vit)
fmt.Println("攻击力:" + g.atk)
fmt.Println("防御力:" + g.def)
}
备忘录类
type RoleStateMemento struct {
vit string
atk string
def string
}
备忘录管理者类
type RoleStateCaretaker struct {
Memento RoleStateMemento
}
测试
//备忘录模式
//大战开始前
lixiaoyao := mementoPattern.GameRole{}
lixiaoyao.GetInstance()
lixiaoyao.StateDisplay()
//保存进度
stateAdmin := mementoPattern.RoleStateCaretaker{}
stateAdmin.Memento = lixiaoyao.SaveState()
//大战开始
lixiaoyao.Fight()
lixiaoyao.StateDisplay()
//恢复进度
lixiaoyao.RecoveryState(stateAdmin.Memento)
lixiaoyao.StateDisplay()