Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Recall & Review
beginner
What is the main purpose of the State pattern?
The State pattern allows an object to change its behavior when its internal state changes, making the object appear to change its class.
Click to reveal answer
intermediate
How does the State pattern help in managing complex conditional logic?
It encapsulates state-specific behavior into separate state classes, reducing large conditional statements and improving code maintainability.
Click to reveal answer
beginner
In the State pattern, what role does the context class play?
The context class maintains an instance of a concrete state object that defines the current state and delegates state-specific behavior to it.
Click to reveal answer
intermediate
What is a key benefit of using the State pattern in system design?
It promotes the Open/Closed Principle by allowing new states to be added without changing existing code.
Click to reveal answer
beginner
Give a real-life example that illustrates the State pattern.
A traffic light system where the light changes from green to yellow to red, and each state has different behavior for cars and pedestrians.
Click to reveal answer
What does the State pattern primarily help to avoid in code?
ALarge conditional statements
BMultiple inheritance
CDatabase transactions
DNetwork latency
✗ Incorrect
The State pattern helps avoid large conditional statements by encapsulating state-specific behavior.
In the State pattern, who is responsible for changing the current state?
AThe client code
BThe database
CThe state interface
DThe context object
✗ Incorrect
The context object manages and changes its current state internally.
Which principle does the State pattern help to follow?
ADependency Inversion Principle
BSingle Responsibility Principle
COpen/Closed Principle
DLiskov Substitution Principle
✗ Incorrect
The State pattern supports the Open/Closed Principle by allowing new states without modifying existing code.
What is the typical structure of the State pattern?
AContext, State interface, Concrete States
BController, Model, View
CClient, Server, Database
DProducer, Consumer, Queue
✗ Incorrect
The State pattern consists of a Context, a State interface, and multiple Concrete State classes.
Which of these is NOT a benefit of the State pattern?
ASimplifies complex state-dependent behavior
BAutomatically optimizes database queries
CImproves code readability
DMakes adding new states easier
✗ Incorrect
The State pattern does not optimize database queries; it focuses on managing state behavior.
Explain how the State pattern changes an object's behavior without changing its class.
Think about how the object delegates tasks to different state objects.
You got /5 concepts.
Describe a real-world scenario where the State pattern can be applied and why it is useful there.
Consider systems like traffic lights, vending machines, or media players.
You got /5 concepts.
Practice
(1/5)
1. What is the main purpose of the State pattern in system design?
easy
A. To provide a global point of access to a resource
B. To create multiple instances of a class efficiently
C. To allow an object to change its behavior when its internal state changes
D. To separate the construction of a complex object from its representation
Solution
Step 1: Understand the role of the State pattern
The State pattern helps an object change its behavior based on its internal state without changing its class.
Step 2: Compare with other design patterns
Other options describe Singleton (A), Prototype (B), and Builder (C) patterns, which are unrelated to state behavior changes.
Final Answer:
To allow an object to change its behavior when its internal state changes -> Option C
Quick Check:
State pattern = behavior change by internal state [OK]
Hint: State pattern changes behavior with state, not object creation [OK]
Common Mistakes:
Confusing State pattern with Singleton or Builder patterns
Thinking it manages object creation instead of behavior
Assuming it provides global access to resources
2. Which of the following is the correct way to define a state interface in a typical State pattern implementation?
easy
A. interface State { void handle(); }
B. class State { void handle() {} }
C. enum State { START, STOP }
D. struct State { int status; }
Solution
Step 1: Identify the correct interface syntax
The State pattern requires a State interface with a method like handle() to define behavior.
Step 2: Eliminate incorrect options
class State { void handle() {} } is a class, not an interface; C is an enum, not behavior; D is a struct without behavior.
Final Answer:
interface State { void handle(); } -> Option A
Quick Check:
State interface defines behavior method [OK]
Hint: State pattern needs interface with behavior method [OK]
Common Mistakes:
Using enum or struct instead of interface/class for behavior
Defining empty methods without interface
Confusing class and interface roles
3. 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?
medium
A. An instance of State
B. An instance of StateB
C. Null (no state)
D. An error occurs
Solution
Step 1: Trace first request()
Initially, ctx.state = State instance. Calling request() calls State.handle(ctx), which sets state to new StateB.
Step 2: Trace second request()
Now ctx.state = StateB instance. Calling request() calls StateB.handle(ctx), which sets state back to new State.
Final Answer:
An instance of State -> Option A
Quick Check:
State and StateB toggle on requests [OK]
Hint: State and StateB toggle on each request call [OK]
Common Mistakes:
Assuming state stays the same after first request
Confusing which handle method is called
Ignoring state changes inside handle methods
4. 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();
medium
A. State interface method signature is incorrect
B. Context's state is never updated inside handle, so state never changes
C. Context does not initialize state before request
D. ConcreteStateA does not implement handle method
Solution
Step 1: Analyze state transitions in handle()
ConcreteStateA.handle() prints a message but does not update Context's state, so no state change occurs.
Step 2: Check other options
State interface method is correct; Context initializes state before request; ConcreteStateA implements handle properly.
Final Answer:
Context's state is never updated inside handle, so state never changes -> Option B
Quick Check:
State transition missing inside handle() [OK]
Hint: State must update Context's state inside handle() [OK]
Common Mistakes:
Forgetting to update state inside handle method
Assuming printing is enough for state change
Ignoring initialization of state before request
5. 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?
hard
A. Use a global variable to track color and update it externally without encapsulating behavior
B. Use a single class with a variable holding the current color and switch behavior using if-else statements
C. Implement the traffic light as a simple timer without state classes
D. Create separate state classes for Green, Yellow, and Red, each implementing a next() method to switch to the next state
Solution
Step 1: Understand State pattern application
The pattern suggests encapsulating each state in its own class with behavior and transitions.
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.
Final Answer:
Create separate state classes for Green, Yellow, and Red, each implementing a next() method to switch to the next state -> Option D
Quick Check:
Separate classes with transitions = State pattern [OK]
Hint: Separate states as classes with next() method for transitions [OK]