The before code shows a simple text editor without undo. The after code applies the command pattern by encapsulating write actions as commands with execute and undo methods. The editor keeps a history stack of commands to support undo by calling undo on the last command.
### Before: No command pattern, no undo support
class TextEditor:
def __init__(self):
self.text = ""
def write(self, words):
self.text += words
editor = TextEditor()
editor.write("Hello")
print(editor.text) # Output: Hello
### After: Command pattern with undo support
class Command:
def execute(self):
pass
def undo(self):
pass
class WriteCommand(Command):
def __init__(self, editor, words):
self.editor = editor
self.words = words
def execute(self):
self.editor.text += self.words
def undo(self):
self.editor.text = self.editor.text[:-len(self.words)]
class TextEditor:
def __init__(self):
self.text = ""
self.history = []
def execute_command(self, command):
command.execute()
self.history.append(command)
def undo(self):
if self.history:
command = self.history.pop()
command.undo()
editor = TextEditor()
cmd1 = WriteCommand(editor, "Hello")
editor.execute_command(cmd1)
print(editor.text) # Output: Hello
editor.undo()
print(editor.text) # Output: ""