Behavioral Pattern

State Pattern

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

12 min readHigh Priority

1What is State Pattern?

Real-World Analogy
Vending Machine

A vending machine behaves differently based on its state: has money, no money, item selected, dispensing. Same button, different behavior.

Document Workflow

A document has states: Draft, Review, Published. The same "edit" action works in Draft but is blocked in Published state.

State pattern extracts state-specific behavior into separate state classes. Instead of using if/switch statements, the object delegates to the current state object, which handles the behavior and may trigger a state transition.

State Machine Example

NoMoneyHasMoneyItemSoldinsertCoinrefunddispensedone

2State vs Strategy Pattern

AspectStateStrategy
PurposeBehavior changes based on internal stateChoose algorithm at runtime
Who decidesState objects trigger transitionsClient chooses strategy
TransitionsStates know about each otherStrategies are independent
ExampleOrder status (Pending → Shipped → Delivered)Sorting algorithm (Quick, Merge, Bubble)

3Implementation

State Pattern - Document Workflow
// ========== State Interface ==========
interface DocumentState {
    void edit(Document doc);
    void review(Document doc);
    void publish(Document doc);
}

// ========== Concrete States ==========
class DraftState implements DocumentState {
    @Override
    public void edit(Document doc) {
        System.out.println("Editing document...");
    }
    
    @Override
    public void review(Document doc) {
        System.out.println("Sending for review...");
        doc.setState(new ReviewState());
    }
    
    @Override
    public void publish(Document doc) {
        System.out.println("Cannot publish draft. Send for review first.");
    }
}

class ReviewState implements DocumentState {
    @Override
    public void edit(Document doc) {
        System.out.println("Returning to draft for edits...");
        doc.setState(new DraftState());
    }
    
    @Override
    public void review(Document doc) {
        System.out.println("Already in review.");
    }
    
    @Override
    public void publish(Document doc) {
        System.out.println("Review complete. Publishing...");
        doc.setState(new PublishedState());
    }
}

class PublishedState implements DocumentState {
    @Override
    public void edit(Document doc) {
        System.out.println("Cannot edit published document. Create new version.");
    }
    
    @Override
    public void review(Document doc) {
        System.out.println("Cannot review published document.");
    }
    
    @Override
    public void publish(Document doc) {
        System.out.println("Already published.");
    }
}

// ========== Context ==========
class Document {
    private DocumentState state;
    private String content;
    
    public Document() {
        this.state = new DraftState();
    }
    
    public void setState(DocumentState state) {
        this.state = state;
        System.out.println("State changed to: " + state.getClass().getSimpleName());
    }
    
    // Delegate to current state
    public void edit() { state.edit(this); }
    public void review() { state.review(this); }
    public void publish() { state.publish(this); }
}

// ========== Usage ==========
public class Main {
    public static void main(String[] args) {
        Document doc = new Document();
        
        doc.edit();      // Works in Draft
        doc.publish();   // Cannot - need review first
        doc.review();    // Moves to Review state
        doc.publish();   // Now works - Published
        doc.edit();      // Cannot edit published
    }
}

4Interview Follow-up Questions

Interview Follow-up Questions

Common follow-up questions interviewers ask

5Key Takeaways

1State pattern encapsulates state-specific behavior in separate classes.
2Object delegates to current state, which handles behavior and transitions.
3Eliminates complex if/else chains checking state.
4States know about each other and control transitions.
5Different from Strategy: State is internal, Strategy is client-chosen.
6Examples: workflow systems, game characters, UI components.