《大话设计模式-Golang》备忘录模式

文章介绍了备忘录模式的概念,通过创建一个角色类`GameRole`,备忘录类`RoleStateMemento`以及管理器类`RoleStateCaretaker`,演示了如何在不破坏封装性的前提下保存和恢复游戏角色的状态。在示例中,角色`lixiaoyao`的游戏状态在大战前后被保存和恢复,展示了备忘录模式在游戏进度备份中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概念

备忘录模式(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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值