Design: State Pattern Implementation
Design and implement the state pattern for a single context object with multiple states. Out of scope are concurrency handling, persistence, and UI integration.
Functional Requirements
Non-Functional Requirements
Jump into concepts and practice - no test required
+----------------+
| Context |
|----------------|
| - state: State |
| + request() |
+--------+-------+
|
v
+----------------+ +----------------+ +----------------+
| State (I) |<-----| ConcreteStateA | | ConcreteStateB |
| + handle() | | + handle() | | + handle() |
+----------------+ +----------------+ +----------------+State pattern in system design?handle() to define behavior.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?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();
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.