Docs

Design Patterns — Fast Recall (Python)

Command — package a request as an object


  • What: wrap an action (+ its args) into an object with `execute()` — and often `undo()`.
  • Why / when: you need to queue, log, schedule, or undo/redo operations — editors, transactions, task queues, macros.
  • Benefit: decouples the invoker (button, queue) from the receiver (who does the work).
  • Recall hook: turning a verb into a noun so you can store it in a list.
1class AddText: 2 def __init__(self, doc, s): self.doc, self.s = doc, s 3 def execute(self): self.doc.append(self.s) 4 def undo(self): self.doc.pop() 5 6doc, history = [], [] 7cmd = AddText(doc, "hi"); cmd.execute(); history.append(cmd) 8print(doc) # ['hi'] 9history.pop().undo() # undo last 10print(doc) # []