备忘录模式(python)

"""
备忘录模式
对一个对象的当前状态进行保存,经过一段时间使用后,可以使用保存的备忘录将对象恢复到备忘录状态
"""


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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值