01 / CALLER
Checkout or fulfilment UI
Sends a command to the same Order. It does not choose the next state itself.
order.send("ship")Calls Order through send(event).
Appearance
STATE / THE IDEA IN A MINUTE
An unpaid order can be paid. A paid order can be shipped. A shipped order cannot be cancelled in our shop. The command means something different depending on where the order is in its lifecycle.
State lets an object delegate behavior to its current state object. When the order moves from Pending to Paid, its next command reaches Paid’s rules. The caller keeps using the same Order.
THE STRUCTURE / ONE CONTEXT, CHANGING BEHAVIOR
A status label tells you where an order is. A state object also knows how it should respond. Explore each stage’s rules below; the live order further down is independent.
01 / CALLER
Sends a command to the same Order. It does not choose the next state itself.
order.send("ship")Calls Order through send(event).
02 / CONTEXT
Holds one current OrderState and the payment, shipment and refund counts.
this.state.handle(event)Delegates to the current state through OrderState.
03 / STATE CONTRACT
Every state accepts a command and returns a decision: accept or reject, an optional effect and the next state.
handle(event): DecisionImplemented by Pending, Paid, Shipped and Cancelled.
04 / CONCRETE STATES
Group the rules for one stage. Pending can pay; Paid can ship. Both can cancel, but only Paid requests a refund.
Returns a decision, including the next state, for Order to install.
In this implementation, states propose transitions and Order applies them. Other State implementations let a state call back into its context. The important boundary is who owns the stage-specific behavior.
FOLLOW ONE ORDER / AT YOUR PACE
Try Ship first, then Pay and Ship. Reset to compare cancellation before and after payment. Commands stay available so you can explore rejection.
Order #1042 starts Pending. Choose a command, then use Next step to follow its execution.
Useful when many operations depend on the same lifecycle stage, and their rules keep changing together. Each state gives those rules a home.
A handful of stable transitions can be clearer as an enum and a transition table. State adds objects and navigation between them. It does not provide persistence, concurrency control or reliable payment processing.
Follow a small checkout as payment, shipping and cancellation rules grow.
Three chapters · a boolean, scattered rules, state objectsBACK FOR A REFRESHERRecall the roles, transition ownership and the difference from Strategy.
Contracts, code and tradeoffs