1
0
Fork 0
design-patterns/python/memento/main.py

65 lines
1.5 KiB
Python

"""实例:
汤宝宝聘请了一位私人助理,帮助他管理日常事务。
他负责记录汤宝宝的状态,以便在需要时恢复到之前的状态。
"""
class Tom:
state: str
def __init__(self, state: str) -> None:
self.state = state
def create_memento(self):
m = Memento(self.state)
print(f"汤宝宝创建了备忘录,状态为:{m.get_state()}")
return m
def restore_memento(self, memento):
self.state = memento.get_state()
print(f"汤宝宝恢复了状态:{self.state}")
class Memento:
__state: str
def __init__(self, state: str) -> None:
self.__state = state
def get_state(self):
return self.__state
def set_state(self, state: str):
self.__state = state
class Assistant:
__memento_list = []
def backup(self, tom: Tom):
self.__memento_list.append(tom.create_memento())
def undo(self, tom: Tom):
if not self.__memento_list:
print("没有备份可供恢复")
return
memento = self.__memento_list.pop()
print("私人助理恢复了汤宝宝的状态")
tom.restore_memento(memento)
if __name__ == "__main__":
print("============= 备忘录模式 =============")
tom = Tom("开心")
print(f"汤宝宝的当前状态:{tom.state}")
assistant = Assistant()
assistant.backup(tom)
tom.state = "生气"
print(f"汤宝宝的当前状态:{tom.state}")
assistant.undo(tom)
print("\n=========== 备忘录模式结束 ===========")