Bird
0
0
LLDsystem_design~3 mins

Why Command pattern for undo in LLD? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if every action you take could be reversed perfectly with just one click?

The Scenario

Imagine you are editing a document by hand, making changes with pen and paper. If you make a mistake, you have to erase everything manually or start over. There is no easy way to go back step-by-step.

The Problem

Manually tracking every change is slow and confusing. You might forget what you changed or how to reverse it. This leads to errors and frustration, especially when changes are complex or frequent.

The Solution

The Command pattern wraps each action as an object with a way to undo it. This lets the system remember and reverse actions easily, like having a magic undo button that works reliably every time.

Before vs After
Before
if (lastChange == 'addText') {
  removeText();
} else if (lastChange == 'deleteText') {
  addText();
}
After
command.execute();
undoStack.push(command);
...
lastCommand = undoStack.pop();
lastCommand.undo();
What It Enables

This pattern enables smooth, reliable undo and redo features that improve user experience and reduce errors.

Real Life Example

Text editors like Microsoft Word or Google Docs use this pattern to let users undo typing, formatting, or deleting with a simple shortcut.

Key Takeaways

Manual undo is error-prone and hard to manage.

Command pattern encapsulates actions and their undo logic.

It makes undo/redo features easy, reliable, and scalable.