Bird
0
0

In the following State pattern code, what is the main issue causing incorrect behavior?

medium📝 Analysis Q14 of 15
LLD - Behavioral Design Patterns — Part 1
In the following State pattern code, what is the main issue causing incorrect behavior?
interface State {
  void handle(Context c);
}

class Context {
  State state;
  void request() {
    state.handle(this);
  }
}

class ConcreteStateA implements State {
  void handle(Context c) {
    // Missing state transition
    System.out.println("State A handling");
  }
}

Context ctx = new Context();
ctx.state = new ConcreteStateA();
ctx.request();
ctx.request();
AState interface method signature is incorrect
BContext's state is never updated inside handle, so state never changes
CContext does not initialize state before request
DConcreteStateA does not implement handle method
Step-by-Step Solution
Solution:
  1. Step 1: Analyze state transitions in handle()

    ConcreteStateA.handle() prints a message but does not update Context's state, so no state change occurs.
  2. Step 2: Check other options

    State interface method is correct; Context initializes state before request; ConcreteStateA implements handle properly.
  3. Final Answer:

    Context's state is never updated inside handle, so state never changes -> Option B
  4. Quick Check:

    State transition missing inside handle() [OK]
Quick Trick: State must update Context's state inside handle() [OK]
Common Mistakes:
MISTAKES
  • Forgetting to update state inside handle method
  • Assuming printing is enough for state change
  • Ignoring initialization of state before request

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes