
备忘录模式是一种行为设计模式,允许在不暴露对象实现细节的情况下保存和恢复对象之前的状态。
主要解决在不破坏封装性的前提下,捕获一个对象的内部状态,并在对象之外保存这个状态,以便在需要时恢复对象到之前的状态。

- #!/usr/bin/env python
- # -*- coding: UTF-8 -*-
- __doc__ = """
- 备忘录模式
- 例:假设有一个文本编辑器应用程序,用户可以在其中编辑文本,并且可以撤销和恢复操作
- """
-
-
- class Memento:
- """备忘录(Memento)"""
-
- def __init__(self, content):
- self._content = content
-
- def get_content(self):
- return self._content
-
-
- class Originator:
- """原发器(Originator)"""
-
- def __init__(self):
- self._content = ""
-
- def type(self, text):
- self._content += text
-
- def get_content(self):
- return self._content
-
- def create_memento(self):
- return Memento(self._content)
-
- def restore_from_memento(self, memento):
- self._content = memento.get_content()
-
-
- class Caretaker:
- """负责人(Caretaker)"""
-
- def __init__(self):
- self._mementos = []
-
- def add_memento(self, memento):
- print(f"当前内容: {memento.get_content()}")
- self._mementos.append(memento)
-
- def get_memento(self, index):
- print("撤销到指定步骤")
- return self._mementos[index]
-
-
- if __name__ == "__main__":
- """
- 当前内容: Hello,
- 当前内容: Hello, world!
- 撤销到指定步骤
- 当前内容: Hello,
- """
- originator = Originator()
- caretaker = Caretaker()
-
- # 用户开始编辑文本
- originator.type("Hello, ")
- memento1 = originator.create_memento()
- caretaker.add_memento(memento1)
-
- # 用户继续编辑文本
- originator.type("world!")
- memento2 = originator.create_memento()
- caretaker.add_memento(memento2)
-
- # 用户撤销操作
- memento = caretaker.get_memento(0)
- originator.restore_from_memento(memento)
-
- print(f"当前内容: {memento.get_content()}")