Bird
0
0

Which design choice best applies the State pattern to handle state transitions and behavior?

hard📝 Trade-off Q15 of 15
LLD - Behavioral Design Patterns — Part 1
You are designing a traffic light system using the State pattern. The traffic light cycles through Green, Yellow, and Red states. Which design choice best applies the State pattern to handle state transitions and behavior?
AUse a global variable to track color and update it externally without encapsulating behavior
BUse a single class with a variable holding the current color and switch behavior using if-else statements
CImplement the traffic light as a simple timer without state classes
DCreate separate state classes for Green, Yellow, and Red, each implementing a <code>next()</code> method to switch to the next state
Step-by-Step Solution
Solution:
  1. Step 1: Understand State pattern application

    The pattern suggests encapsulating each state in its own class with behavior and transitions.
  2. Step 2: Evaluate options for scalability and clarity

    Create separate state classes for Green, Yellow, and Red, each implementing a next() method to switch to the next state cleanly separates states and their transitions. Options B, C, and D mix logic or lack encapsulation, reducing maintainability.
  3. Final Answer:

    Create separate state classes for Green, Yellow, and Red, each implementing a next() method to switch to the next state -> Option D
  4. Quick Check:

    Separate classes with transitions = State pattern [OK]
Quick Trick: Separate states as classes with next() method for transitions [OK]
Common Mistakes:
MISTAKES
  • Using if-else instead of separate state classes
  • Not encapsulating state behavior inside classes
  • Relying on external variables without behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes