📅  最后修改于: 2023-12-03 14:44:15.400000             🧑  作者: Mango
Memento模式是一种行为型设计模式,它可在不暴露对象实现细节的情况下保存和恢复对象的内部状态。 该模式提供了一种在恢复状态时避免将实现细节暴露给客户端的方法。
Memento模式由三个主要组件组成:
from datetime import datetime
class Originator:
'''
原始对象
'''
def __init__(self, state):
self.state = state
def do_something(self):
'''
记录状态变化
'''
self.state = f"{self.state} {datetime.utcnow()}"
def save(self):
'''
保存状态
'''
return Memento(self.state)
def restore(self, memento):
'''
恢复状态
'''
self.state = memento.get_state()
class Memento:
'''
备忘录
'''
def __init__(self, state):
self.state = state
def get_state(self):
'''
获取状态
'''
return self.state
class Caretaker:
'''
管理器
'''
def __init__(self, originator):
self.mementos = []
self.originator = originator
def backup(self):
'''
保存状态
'''
self.mementos.append(self.originator.save())
def undo(self):
'''
恢复最后一次状态
'''
if self.mementos:
memento = self.mementos.pop()
self.originator.restore(memento)
originator = Originator("initial state")
caretaker = Caretaker(originator)
# 记录状态变化
originator.do_something()
print(f'current state: {originator.state}')
# 保存状态
caretaker.backup()
# 再一次记录状态变化
originator.do_something()
print(f'current state: {originator.state}')
# 再次保存状态
caretaker.backup()
# 恢复最后一次状态
caretaker.undo()
print(f'current state: {originator.state}')
# 恢复初始状态
caretaker.undo()
print(f'current state: {originator.state}')
以上代码的输出结果如下:
current state: initial state 2022-08-24 08:51:23.068261
current state: initial state 2022-08-24 08:51:23.068261 2022-08-24 08:51:52.384158
current state: initial state 2022-08-24 08:51:23.068261
current state: initial state