"""
备忘录模式
对一个对象的当前状态进行保存,经过一段时间使用后,可以使用保存的备忘录将对象恢复到备忘录状态
"""
class GameRole(object):
"""
游戏角色
"""
def __init__(self, live=None, magic=None, strong=None):
self._live = live
self._magic = magic
self._strong = strong
def save_memo(self):
"""
存档
:return:
"""
memo = Memo()
memo.live = self._live
memo.strong = self._strong
return memo
def read_memo(self, memo):
"""
读档
:param memo: 备忘录
:return:
"""
print("我胡汉三又回来了")
self._live = memo.live
self._strong = memo.strong
def fight(self):
"""
打boss
:return:
"""
print("打boss:这boss好难打,打不过,放弃了")
self._live = 10
self._magic = 10
self._strong = 10
def display(self):
"""
资料展示
:return:
"""
print("游戏角色资料:")
print("生命值:" + str(self._live))
print("魔力值:" + str(self._magic))
print("攻击力:" + str(self._strong))
print("")
class Memo(object):
def __init__(self, live=None, strong=None):
self._live = live
self._strong = strong
@property
def live(self):
return self._live
@live.setter
def live(self, live):
self._live = live
@property
def strong(self):
return self._strong
@strong.setter
def strong(self, strong):
self._strong = strong
class MemoMarket(object):
"""
备忘录仓库
"""
def __init__(self):
self.memo_dict = dict()
def append_memo(self, msg, memo):
self.memo_dict[msg] = memo
def get_memo(self, msg):
return self.memo_dict[msg]
if __name__ == '__main__':
game = GameRole(100, 100, 100)
game.display()
memo_market = MemoMarket()
msg = "刚才"
memo_market.append_memo(msg, game.save_memo())
game.fight()
boss_msg = "boss存档"
memo_market.append_memo(boss_msg, game.save_memo())
game.display()
print("回到未打boss前")
game.read_memo(memo_market.get_memo(msg))
game.display()
print("回到打boss界面")
game.read_memo(memo_market.get_memo(boss_msg))
game.display()
备忘录模式(python)
最新推荐文章于 2022-10-20 16:26:57 发布