🧩State Pattern – Overview
🧠 Concept
🧱 Key Roles
Role
Description
💻 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.");
}
}🧠 Flow Summary (Step-by-Step)
Step
Current State
Action
Next State
Output
🪜 Summary
📊 Real-world Analogy
Last updated