class Memento:
def __init__(self, state):
self._state = state
def get_state(self):
return self._state
class TextEditor:
def __init__(self):
self._text = ""
def type_text(self, text):
self._text += text
def save(self):
return Memento(self._text)
def restore(self, memento):
self._text = memento.get_state()
def get_text(self):
return self._text
class Caretaker:
def __init__(self):
self._history = []
def backup(self, memento):
self._history.append(memento)
def undo(self):
if not self._history:
return None
return self._history.pop()
def main():
editor = TextEditor()
caretaker = Caretaker()
# Набираем текст и сохраняем состояния
editor.type_text("Hello, ")
caretaker.backup(editor.save())
print("Current text:", editor.get_text()) # Current text: Hello,
editor.type_text("world!")
caretaker.backup(editor.save())
print("Current text:", editor.get_text()) # Current text: Hello, world!
# Вносим изменения и сохраняем новое состояние
editor.type_text(" How are you?")
print("Current text:", editor.get_text()) # Current text: Hello, world! How are you?
# Откатываемся к предыдущему состоянию
editor.restore(caretaker.undo())
print("After undo:", editor.get_text()) # After undo: Hello, world!
# Ещё одно откатывание
editor.restore(caretaker.undo())
print("After second undo:", editor.get_text()) # After second undo: Hello,
main()
Current text: Hello,
Current text: Hello, world!
Current text: Hello, world! How are you?
After undo: Hello, world!
After second undo: Hello,