Bird
Raised Fist0
LLDsystem_design~5 mins

Command pattern in LLD - Cheat Sheet & Quick Revision

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Recall & Review
beginner
What is the main purpose of the Command pattern?
The Command pattern encapsulates a request as an object, allowing you to parameterize clients with queues, requests, and operations. It separates the object that invokes the operation from the one that knows how to perform it.
Click to reveal answer
beginner
Name the four main components of the Command pattern.
1. Command: declares an interface for executing an operation.
2. ConcreteCommand: implements the Command interface and defines the binding between a Receiver and an action.
3. Receiver: knows how to perform the operations.
4. Invoker: asks the command to carry out the request.
Click to reveal answer
intermediate
How does the Command pattern help in implementing undo functionality?
By storing command objects that represent actions, the system can reverse or undo actions by calling an undo method on the stored commands, since each command knows how to undo its own operation.
Click to reveal answer
intermediate
Explain how the Command pattern supports queuing and logging of requests.
Since commands are objects, they can be stored in queues or logs. This allows requests to be executed later, retried, or audited by replaying the stored commands.
Click to reveal answer
beginner
What real-life example can help understand the Command pattern?
Think of a remote control (Invoker) that sends commands to devices like a TV or stereo (Receivers). Each button press is a command object that tells the device what to do, separating the button from the device's internal workings.
Click to reveal answer
Which component in the Command pattern knows how to perform the actual work?
AInvoker
BReceiver
CConcreteCommand
DClient
What is the role of the Invoker in the Command pattern?
ADefines the command interface
BPerforms the actual operation
CExecutes the command
DStores and calls commands
How does the Command pattern help with undo operations?
ABy logging errors
BBy storing the state of the system
CBy encapsulating requests as objects with undo methods
DBy using callbacks
Which of these is NOT a benefit of the Command pattern?
AAutomatically optimizes performance
BSupports queuing requests
CDecouples sender and receiver
DEnables logging and undo
In the Command pattern, what does the ConcreteCommand do?
AImplements the command and binds it to a receiver
BStores commands in a queue
CInvokes the command
DDefines the interface for commands
Describe the Command pattern and explain its main components and their roles.
Think about how requests are turned into objects and who does what.
You got /5 concepts.
    Explain how the Command pattern can be used to implement undo functionality and request queuing.
    Focus on how commands can be saved and reversed.
    You got /5 concepts.

      Practice

      (1/5)
      1. What is the main purpose of the Command pattern in system design?
      easy
      A. To create multiple instances of a class efficiently
      B. To ensure only one instance of a class exists
      C. To define a family of algorithms and make them interchangeable
      D. To encapsulate a request as an object, allowing parameterization and queuing of requests

      Solution

      1. Step 1: Understand the Command pattern role

        The Command pattern encapsulates a request as an object, which allows you to parameterize clients with queues, requests, and operations.
      2. Step 2: Compare with other patterns

        Creating multiple instances relates to Prototype or Factory, a family of algorithms to Strategy, and a single instance to Singleton; these are not Command.
      3. Final Answer:

        To encapsulate a request as an object, allowing parameterization and queuing of requests -> Option D
      4. Quick Check:

        Command pattern = encapsulate request [OK]
      Hint: Command pattern = wrap action as object for flexibility [OK]
      Common Mistakes:
      • Confusing Command with Singleton or Factory patterns
      • Thinking Command creates instances instead of encapsulating actions
      • Mixing Command with Strategy pattern
      2. Which of the following is the correct method signature for the execute method in a Command interface?
      easy
      A. void execute(String[] args);
      B. void execute();
      C. boolean execute(String commandName);
      D. int execute(int commandId);

      Solution

      1. Step 1: Recall Command interface basics

        The Command interface typically defines a simple execute() method without parameters to perform the action.
      2. Step 2: Analyze options

        The options with parameters (String[], int commandId, String commandName) or return types are not standard in Command pattern interfaces; the command object itself holds necessary data.
      3. Final Answer:

        void execute(); -> Option B
      4. Quick Check:

        Command execute method = void execute() [OK]
      Hint: Command execute usually has no parameters [OK]
      Common Mistakes:
      • Adding parameters to execute method unnecessarily
      • Confusing Command with other patterns that require arguments
      • Assuming execute returns a value
      3. Given the following code snippet implementing the Command pattern, what will be the output?
      class Light {
        turnOn() { console.log('Light is ON'); }
        turnOff() { console.log('Light is OFF'); }
      }
      
      class TurnOnCommand {
        constructor(light) { this.light = light; }
        execute() { this.light.turnOn(); }
      }
      
      class TurnOffCommand {
        constructor(light) { this.light = light; }
        execute() { this.light.turnOff(); }
      }
      
      class RemoteControl {
        setCommand(command) { this.command = command; }
        pressButton() { this.command.execute(); }
      }
      
      const light = new Light();
      const remote = new RemoteControl();
      remote.setCommand(new TurnOnCommand(light));
      remote.pressButton();
      remote.setCommand(new TurnOffCommand(light));
      remote.pressButton();
      medium
      A. Light is ON\nLight is OFF
      B. Light is OFF\nLight is ON
      C. Light is ON\nLight is ON
      D. Light is OFF\nLight is OFF

      Solution

      1. Step 1: Trace first command execution

        The remote sets the command to TurnOnCommand and calls execute, which calls light.turnOn(), printing 'Light is ON'.
      2. Step 2: Trace second command execution

        The remote sets the command to TurnOffCommand and calls execute, which calls light.turnOff(), printing 'Light is OFF'.
      3. Final Answer:

        Light is ON\nLight is OFF -> Option A
      4. Quick Check:

        TurnOn then TurnOff commands print ON then OFF [OK]
      Hint: Follow command set and execute calls step-by-step [OK]
      Common Mistakes:
      • Mixing order of commands
      • Assuming commands execute immediately without setting
      • Confusing method names turnOn and turnOff
      4. In the following code, what is the main issue that prevents the Command pattern from working correctly?
      class Light {
        turnOn() { console.log('Light is ON'); }
      }
      
      class TurnOnCommand {
        constructor() { }
        execute() { this.light.turnOn(); }
      }
      
      const light = new Light();
      const command = new TurnOnCommand();
      command.execute();
      medium
      A. The execute method should return a value
      B. The Light class is missing the turnOff method
      C. The TurnOnCommand constructor does not receive or store the Light object
      D. The command object is not instantiated properly

      Solution

      1. Step 1: Check TurnOnCommand constructor

        The constructor does not accept or assign the Light object to this.light, so this.light is undefined.
      2. Step 2: Analyze execute method call

        Calling this.light.turnOn() fails because this.light is undefined, causing an error.
      3. Final Answer:

        The TurnOnCommand constructor does not receive or store the Light object -> Option C
      4. Quick Check:

        Missing light reference in command = error [OK]
      Hint: Ensure command stores receiver object before execute [OK]
      Common Mistakes:
      • Ignoring missing receiver object in command
      • Thinking missing turnOff method causes error here
      • Assuming execute must return a value
      5. You are designing a text editor with undo functionality using the Command pattern. Which design choice best supports undo operations efficiently?
      hard
      A. Store a history stack of Command objects and call an undo() method on the last command
      B. Keep a log of all text changes as strings and replay them to undo
      C. Use a single Command object that modifies text directly without history
      D. Implement undo by reloading the entire document from disk

      Solution

      1. Step 1: Understand undo with Command pattern

        Each Command object should implement both execute() and undo() methods to reverse its action.
      2. Step 2: Evaluate design choices

        Storing a history stack of Command objects allows calling undo() on the last command efficiently. Other options either lack command encapsulation or are inefficient.
      3. Final Answer:

        Store a history stack of Command objects and call an undo() method on the last command -> Option A
      4. Quick Check:

        Undo = command history stack with undo() [OK]
      Hint: Undo needs command history with undo method [OK]
      Common Mistakes:
      • Using string logs instead of command objects
      • Not implementing undo in commands
      • Reloading entire document is inefficient