teacher
Sign in

State

Let an object change its behaviour when its internal state changes by moving each state's rules into its own class.

22 min4 interactive

The problem it solves

An order moves through a life: new, paid, shipped. Cancelling is allowed early and not later. The first attempt is usually flags and ifs:

void cancel() {
    if (state == NEW || state == PAID) state = CANCELLED;
    else System.out.println("cannot cancel");
}

That is fine for one action. Then pay, ship, refund and return each get their own chain of state checks. Add one state and you edit every method. Rules for one state are scattered across the class.

State gives each state its own class. The object (the context) holds a pointer to the current state object and forwards every action to it. Changing state means swapping the pointer. All the rules for "PAID" now sit in one class.

1 of 8