A Snapshot of Time, Undoing the Past, Embracing the Future
In essence, the Memento Design Pattern empowers your code to travel through time, capturing fleeting moments and revisiting them at will. This opens doors for undo/redo functionality, versioning, and alternative paths, fostering a dynamic and flexible environment within your program.
class Memento:
def __init__(self, state):
self.state = state
class TextEditor:
def __init__(self):
self.text = ""
self.history = []
self.redo_history = []
def write(self, text):
self.history.append(Memento(self.text)) # Save current state before modification
self.text += text
def undo(self):
if self.history:
memento = self.history.pop()
self.redo_history.append(Memento(self.text)) # Add current state to redo history
self.text = memento.state
def redo(self):
if self.redo_history:
memento = self.redo_history.pop()
self.history.append(Memento(self.text)) # Add current state to undo history
self.text = memento.state
# Client code using the Memento pattern
editor = TextEditor()
editor.write("Hello")
editor.write(" world!")
print(editor.text) # Output: Hello world!
editor.undo()
print(editor.text) # Output: Hello
editor.redo()
print(editor.text) # Output: Hello world!