备忘录模式说通俗点就相当于一个游戏存档,一般我们玩游戏打BOSS前都会保存一下,如果打BOSS失败了就读取存档再来一遍,这里面涉及三个对象,英雄:你控制的游戏角色,存档:用来保存英雄的状态数据,存档管理员:帮你执行保存和读取的工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| class StatusMemento: def __init__(self, attack, defense): self.attack = attack self.defense = defense
def __str__(self): return f"存档:攻击力:{self.attack}, 防御力:{self.defense}"
def __repr__(self): return f"攻击力:{self.attack}, 防御力:{self.defense}"
class Hero: def __init__(self, attack, defense): self.attack = attack self.defense = defense
def get_injured(self): self.attack = 50 self.defense = 50 print("英雄受伤了")
def save_status(self): print("存档") return StatusMemento(self.attack, self.defense)
def recover_status(self, status): print("恢复存档") self.attack = status.attack self.defense = status.defense
def current_status(self): print(f"角色的当前状态为 攻击力:{self.attack}, 防御力:{self.defense}")
class Caretaker: statuses = {} num = 0
@classmethod def add(cls, status): cls.num += 1 print(f"存档增加状态 --- {status} ---") s = {cls.num: status} cls.statuses.update(s)
@classmethod def current_statuses(cls): print(f"当前所有存档为 {cls.statuses}")
hero = Hero(100, 100) hero.current_status() Caretaker.add(hero.save_status())
hero.get_injured() hero.current_status() Caretaker.add(hero.save_status())
Caretaker.current_statuses() hero.recover_status(Caretaker.statuses[1]) hero.current_status()
hero.recover_status(Caretaker.statuses[2]) hero.current_status()
|