π§©State Pattern β Overview
π§ Concept
The State Pattern allows an object to change its behavior when its internal state changes. It appears as if the objectβs class changes at runtime.
π It removes complex
if-elseorswitchstatements for state transitions and encapsulates state-specific behavior into separate classes.
π§± Key Roles
Context
The main object whose behavior changes depending on its state.
State (Interface)
Declares methods that represent behavior in a given state.
ConcreteState
Implements behavior specific to a particular state.
π» Java Example β Report Generator (States: Draft β Review β Published)
// Context
class ReportContext {
private ReportState state;
public ReportContext() {
this.state = new DraftState(); // initial state
}
public void setState(ReportState state) {
this.state = state;
}
public void request() {
state.handle(this);
}
}
// State interface
interface ReportState {
void handle(ReportContext context);
}
// Concrete States
class DraftState implements ReportState {
public void handle(ReportContext context) {
System.out.println("Report in Draft β Sending for Review...");
context.setState(new ReviewState());
}
}
class ReviewState implements ReportState {
public void handle(ReportContext context) {
System.out.println("Report under Review β Publishing...");
context.setState(new PublishedState());
}
}
class PublishedState implements ReportState {
public void handle(ReportContext context) {
System.out.println("Report already Published. No further actions.");
}
}β Usage Example:
π§ Flow Summary (Step-by-Step)
1οΈβ£
Draft
request()
Review
"Report in Draft β Sending for Review..."
2οΈβ£
Review
request()
Published
"Report under Review β Publishing..."
3οΈβ£
Published
request()
Published
"Report already Published. No further actions."
πͺ Summary
Encapsulates state-specific behavior into separate classes.
Eliminates conditional logic for state transitions.
Makes adding new states easier without modifying the core logic.
Promotes Open/Closed and Single Responsibility principles.
π Real-world Analogy
π Document Workflow: A report changes its behavior as it moves through stages: Draft β Review β Published β each state has its own rules and actions.
Last updated