跟原型模式很像,不过在原型模式中保存对象的一切,而备忘录模式中只保存恢复时需要的数据。
#encoding=utf-8
#
#by panda
#备忘录模式
def printInfo(info):
print unicode(info, 'utf-8').encode('gbk')
#Originator:游戏角色类
class GameCharacter():
vitality = 0 #生命力
attack = 0 #攻击力
defense = 0 #防御力
def DisplayState(self):
printInfo('角色当前状态')
printInfo('\t生命力:%d' % self.vitality)
printInfo('\t攻击力:%d' % self.attack)
printInfo('\t防御力:%d' % self.defense)
def InitState(self):
self.vitality = 100
self.attack = 100
self.defense = 100
def Fight(self):
self.vitality = 0
self.attack = 0
self.defense = 0
#保存状态
def SaveState(self):
return RoleStateMemento(self.vitality, self.attack, self.defense)
#恢复状态
def RecoveryState(self, memento):
self.vitality = memento.vitality
self.attack = memento.attack
self.defense = memento.defense
#Memento:角色状态存储箱
class RoleStateMemento():
vitality = 0 #生命力
attack = 0 #攻击力
defense = 0 #防御力
def __init__(self, vitality, attack, defense):
self.vitality = vitality
self.attack = attack
self.defense = defense
#Caretaker:角色状态管理者
class RoleStateCaretaker():
memento = None
def clientUI():
printInfo('----大战Boss前----')
id1 = GameCharacter()
id1.InitState()
id1.DisplayState()
printInfo('----保存进度----')
stateAdmin = RoleStateCaretaker()
stateAdmin.memento = id1.SaveState()
printInfo('----大战boss,损耗严重----')
id1.Fight()
id1.DisplayState()
printInfo('----恢复之前的状态----')
id1.RecoveryState(stateAdmin.memento)
id1.DisplayState()
return
if __name__ == '__main__':
clientUI();
类图: