ProgramGuru

State Pattern

State: start from the problem

See the responsibilities

ContextOwns current lifecycle state
ActionArrives under an event identity
State ruleAccepts or rejects the transition
Next stateBecomes the new valid context
Context: Owns current lifecycle state → Action: Arrives under an event identity → State rule: Accepts or rejects the transition → Next state: Becomes the new valid context

An order can be draft, submitted or paid. The same action should be accepted or rejected according to its current state. Scattered conditionals can permit impossible transitions.

This is a behavioral pattern lesson. Follow the responsibilities, inspect the small JavaScript example and compare the design choices. The example is local teaching code; its boundary is explained before you apply the idea to a real service.

What you’ll learn

  • Explain the problem State addresses and the roles involved.
  • Follow the example and distinguish this pattern from nearby alternatives.
  • Choose when the benefit justifies the extra responsibilities and testing.

How the responsibilities work

State places state-specific behaviour behind a shared action interface and lets the context delegate to its current state. Transitions choose the next valid state. The design should make invalid events explicit rather than silently accepting them.

Our small transition table represents the same responsibility without a class per state. submit is allowed from draft, and pay is allowed from submitted. A successful local transition does not demonstrate safe concurrent database updates.

Follow a small example

Read the JavaScript from top to bottom and compare the expected output. The values are chosen to make this pattern’s responsibility visible. This example runs in one local execution context; it does not create remote services, durable storage or production access controls.

JavaScript · local teaching example

let state = 'draft';
const transitions = {draft: {submit: 'submitted'}, submitted: {pay: 'paid'}, paid: {}};
function act(event) {
  const next = transitions[state][event];
  if (!next) return 'rejected';
  state = next;
  return state;
}
console.log(act('pay'));
console.log(act('submit'));
console.log(act('pay'));

Expected output

rejected
submitted
paid

Choose a design and inspect the consequence

Compare the design choices

Two workers try to transition the same stored order.
An event does not fit the current state.

Compare the visible consequences. With JavaScript enabled, choose an option in each scenario to assemble your decision record.

This is an exploratory design exercise. It does not run infrastructure, measure capacity or replace the lesson’s quiz.

Use the consequences to explain your decision, including the simpler alternative.

Apply the pattern to two situations. Select one option in each situation to build a decision record. Every option and its consequence stays visible, and you can change your choices.

When it helps—and what it costs

Use it for a meaningful lifecycle with state-dependent actions, such as upload, order or job status. Keep transition ownership and event identity deliberate.

Many states can obscure the lifecycle unless transitions are documented. Persistent concurrent transitions need version checks or a supported atomic operation. A local state table is not a durable workflow engine.

Distinguish the neighbouring patterns

Strategy chooses an algorithm for a context. State models behaviour driven by lifecycle and transitions. A saga uses a recorded workflow across local transactional owners.

Follow chosen algorithms versus lifecycle state, multi-owner workflows, media readiness transitions to compare the specific responsibility before combining patterns.

Check your pattern reasoning

Why is pay rejected from draft?
Choose one answer. You can try again.

Answer and explanation

The state contract only permits pay after submission.

Not every event is valid in every state.

Check your pattern reasoning

What else is needed for concurrent persistent order transitions?
Choose one answer. You can try again.

Answer and explanation

An appropriate atomic update or version/transaction rule.

Two writers must not independently violate the lifecycle.

Name the responsibility before choosing the pattern

For State, describe the problem, the participating roles and the observable contract. Use the example as a starting point and test the boundaries identified in the trade-offs. A pattern name alone does not establish correctness or performance.

Return to the design-pattern guide to compare families, or apply the idea alongside media readiness transitions.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Chain of Responsibility Pattern →