Bird
0
0

Consider this simplified code snippet using the State pattern:

medium📝 Analysis Q13 of 15
LLD - Behavioral Design Patterns — Part 1
Consider this simplified code snippet using the State pattern:
class Context {
  State state;
  void request() { state.handle(this); }
  void setState(State s) { state = s; }
}

class State {
  void handle(Context c) { c.setState(new StateB()); }
}

class StateB extends State {
  void handle(Context c) { c.setState(new State()); }
}

Context ctx = new Context();
ctx.setState(new State());
ctx.request();
ctx.request();
What is the final state of ctx after these two requests?
AAn instance of State
BAn instance of StateB
CNull (no state)
DAn error occurs
Step-by-Step Solution
Solution:
  1. Step 1: Trace first request()

    Initially, ctx.state = State instance. Calling request() calls State.handle(ctx), which sets state to new StateB.
  2. Step 2: Trace second request()

    Now ctx.state = StateB instance. Calling request() calls StateB.handle(ctx), which sets state back to new State.
  3. Final Answer:

    An instance of State -> Option A
  4. Quick Check:

    State and StateB toggle on requests [OK]
Quick Trick: State and StateB toggle on each request call [OK]
Common Mistakes:
MISTAKES
  • Assuming state stays the same after first request
  • Confusing which handle method is called
  • Ignoring state changes inside handle methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes