Bird
0
0

Identify the flaw in this State pattern code snippet:

medium📝 Analysis Q7 of 15
LLD - Behavioral Design Patterns — Part 1
Identify the flaw in this State pattern code snippet:
class Context {
  State state;
  Context(State s) { state = s; }
  void request() { state.handle(this); }
}

interface State {
  void handle(Context c);
}

class ConcreteState implements State {
  public void handle(Context c) {
    // Missing state transition logic
  }
}
AState interface should return a new State instead of void.
BContext's request method should not pass itself to handle method.
CConcreteState does not update the Context's state, causing no state change.
DContext constructor should not accept initial State.
Step-by-Step Solution
Solution:
  1. Step 1: Review ConcreteState's handle method

    It lacks code to update the Context's current state.
  2. Step 2: Understand State pattern behavior

    Each concrete state should be able to change the Context's state to another state if needed.
  3. Final Answer:

    ConcreteState does not update the Context's state, causing no state change. -> Option C
  4. Quick Check:

    State transitions require explicit context state updates [OK]
Quick Trick: Concrete states must update context state explicitly [OK]
Common Mistakes:
MISTAKES
  • Assuming state changes automatically without code
  • Misunderstanding Context's role in state transitions
  • Expecting handle to return new state

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes