备忘录模式,类似于撤销功能,提供保存并恢复之前状态的功能。
class Momento(object):
def __init__(self):
super().__init__()
self.dct = {}
def set_status(self, dct):
self.dct = {}
for key in dct:
if not key.startswith('_'):
self.dct[key] = dct[key]
def get_status(self):
return self.dct
class Obj(object):
def __init__(self, a):
super().__init__()
self.attribute_a = a
self._momento = Momento()
def set_a(self, status):
self.backup_current_status()
self.attribute_a = status
def restore_previous_status(self):
self.__dict__.update(self._momento.get_status())
def backup_current_status(self):
self._momento.set_status(self.__dict__)
def __str__(self):
return "attribute_a: " + self.attribute_a + '\n'
def main():
obj = Obj('a')
obj.set_a('aa')
print('current_status:\n', obj)
obj.restore_previous_status()
print('previous_status:\n', obj)
if __name__ == '__main__':
main()
网友评论