Before applying the Memento pattern, the Editor exposes its internal state directly, risking tight coupling and breaking encapsulation. After applying the pattern, the Editor creates a Memento object to store its state, and the Caretaker manages these mementos. This keeps the Editor's state private and allows safe undo operations.
### Before (without Memento pattern):
class Editor:
def __init__(self):
self.content = ""
def type(self, words):
self.content += words
def save(self):
# No encapsulation, exposes internal state
return self.content
def restore(self, content):
self.content = content
editor = Editor()
editor.type("Hello ")
saved = editor.save()
editor.type("World!")
print(editor.content) # Hello World!
editor.restore(saved)
print(editor.content) # Hello
### After (with Memento pattern):
class Memento:
def __init__(self, content):
self._content = content
def get_content(self):
return self._content
class Editor:
def __init__(self):
self._content = ""
def type(self, words):
self._content += words
def save(self):
return Memento(self._content)
def restore(self, memento):
self._content = memento.get_content()
def get_content(self):
return self._content
class Caretaker:
def __init__(self):
self._mementos = []
def save_state(self, editor):
self._mementos.append(editor.save())
def undo(self, editor):
if not self._mementos:
return
memento = self._mementos.pop()
editor.restore(memento)
editor = Editor()
caretaker = Caretaker()
editor.type("Hello ")
caretaker.save_state(editor)
editor.type("World!")
print(editor.get_content()) # Hello World!
caretaker.undo(editor)
print(editor.get_content()) # Hello