备忘录模式保存一个对象的某个状态,以便在适当的时候恢复对象。

应用实例:

  1. 游戏存档
  2. windows的ctrl + z
  3. 浏览器的后退

    Demo

    ```python “”” 备忘录模式 “””

class Memento: “”” 备忘录: 负责存储Originator的内部状态 “””

  1. def __init__(self, state):
  2. self.state = state
  3. def set_state(self, state):
  4. self.state = state

class Originator: “”” 发起人: 记录当前时刻的内部状态信息,提供创建备忘录和恢复备忘录数据的功能 “””

def __init__(self):
    self.__state = None

@property
def state(self):
    return self.__state

@state.setter
def state(self, state):
    self.__state = state

def save_state_to_memento(self):
    return Memento(self.__state)

def get_state_from_memento(self, memento):
    self.__state = memento.state

class CareTaker: “”” 管理者: 对备忘录进行管理,提供保存和获取备忘录的功能,但其不能对备忘录的内容进行访问和修改 “””

def __init__(self):
    self.__mementos = []

def add(self, memento):
    self.__mementos.append(memento)

def get(self, index):
    return self.__mementos[index]

if name == ‘main‘: originator = Originator() care_taker = CareTaker() originator.state = “State #1” originator.state = “State #2” care_taker.add(originator.save_state_to_memento()) originator.state = “State #3” care_taker.add(originator.save_state_to_memento()) originator.state = “State #4” originator.get_state_from_memento(care_taker.get(0)) print(f”state : {originator.state}”) originator.get_state_from_memento(care_taker.get(1)) print(f”state : {originator.state}”)

```