Bird
Raised Fist0

Given the following code snippet implementing the Command pattern, what will be the output?

medium📝 Analysis Q13 of Q15
LLD - Behavioral Design Patterns — Part 1
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();
ALight is ON\nLight is OFF
BLight is OFF\nLight is ON
CLight is ON\nLight is ON
DLight is OFF\nLight is OFF
Step-by-Step Solution
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]
Quick Trick: Follow command set and execute calls step-by-step [OK]
Common Mistakes:
MISTAKES
  • Mixing order of commands
  • Assuming commands execute immediately without setting
  • Confusing method names turnOn and turnOff

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes