Bird
0
0
LLDsystem_design~3 mins

Why Command pattern in LLD? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could press a button and instantly undo or schedule any action without rewriting your code?

The Scenario

Imagine you have a remote control with many buttons, and each button does a different task. Now, you want to add undo and redo features, or queue commands to run later. Doing all this by writing separate code for each button and feature quickly becomes messy and confusing.

The Problem

Manually handling each action means you mix the code for what to do with when and how to do it. This leads to tangled code that is hard to change or extend. Adding new commands or features like undo requires rewriting many parts, increasing bugs and slowing development.

The Solution

The Command pattern wraps each action into its own object. This separates the 'what to do' from 'when and how to do it'. It makes adding new commands, undo, redo, or queuing simple and clean without changing existing code.

Before vs After
Before
if(button == 'play') { playSong(); } else if(button == 'stop') { stopSong(); } // no undo support
After
command = new PlayCommand(song); remote.setCommand(command); remote.pressButton(); // supports undo, redo, queue
What It Enables

It enables flexible, reusable, and extendable command execution with features like undo, redo, and scheduling without messy code changes.

Real Life Example

In text editors, every user action like typing or deleting is a command object. This lets the editor easily undo or redo actions by replaying or reversing these commands.

Key Takeaways

Separates actions into command objects for clean code.

Makes adding undo, redo, and queuing easy.

Improves flexibility and maintainability of complex systems.