Skip to content
Veltoryx Technologies
ProLesson 6.4Intermediate8 min readUpdated 31 October 2026

State Pattern

Learn how an object can change its behaviour when its state changes by moving each state into its own class, using a document publishing workflow, and how State differs from Strategy.

Think about the power button on the side of your phone. If the screen is off, pressing it wakes the phone. If the phone is ringing, pressing it silences the ring. If you are in a call, pressing it locks the screen or ends the call, depending on settings. It is the same button and the same press, but the result depends on what state the phone is in.

Many objects in software are like this. An order can be new, paid, shipped or cancelled. A document can be a draft, in review or published. A vending machine can be waiting for coins, holding a coin or dispensing a drink. In each state, the same action means something different, or is not allowed at all. The State pattern is the clean way to write such objects.

01The problem: if/else on the status in every method

Let us model a document with a publishing workflow. A document starts as a draft. The author submits it for review. A reviewer can approve it, which publishes it, or reject it, which sends it back to draft. A published document can be archived.

A natural first version stores the status as a text value and checks it in every method:

Before: every method checks the status
public class Document {

    private String status = "DRAFT";

    public void submit() {
        if (status.equals("DRAFT")) {
            status = "IN_REVIEW";
        } else {
            throw new IllegalStateException("Cannot submit in " + status);
        }
    }

    public void approve() {
        if (status.equals("IN_REVIEW")) {
            status = "PUBLISHED";
        } else {
            throw new IllegalStateException("Cannot approve in " + status);
        }
    }

    public void reject() {
        if (status.equals("IN_REVIEW")) {
            status = "DRAFT";
        } else {
            throw new IllegalStateException("Cannot reject in " + status);
        }
    }

    public void archive() {
        if (status.equals("PUBLISHED")) {
            status = "ARCHIVED";
        } else {
            throw new IllegalStateException("Cannot archive in " + status);
        }
    }
}

With four states and four actions it is still readable. But real workflows grow. Add "Scheduled", "Needs legal approval" and "Withdrawn", and:

  • Every method grows a longer chain of if checks.
  • The rules of one state (what it allows and where it goes next) are spread across every method, so it is hard to see the whole picture of a single state.
  • Adding a new state means editing every method, with a high risk of missing one.
  • A typo in a status string such as "PUBLISED" is not caught by the compiler.

Loading the rest of the lesson…