Cheatsheet

State

Intent

Let an object change its behaviour when its situation changes, by putting each situation in its own object instead of spreading conditions across every method.

Structure (UML)

Spring contextTRIALFROZENMembershipControllerMembershipServiceMembershipACTIVEEXPIREDMembershipRepositorymembership tableAthlete

Participants

  • Context (Membership), what the rest of the app uses; it hands every action to its current state
  • State (MembershipState), what every state can do, with a default behaviour
  • ConcreteState (TRIAL, ACTIVE, FROZEN, EXPIRED), each situation with its rules and its transitions

Membership.java

public void checkIn() { state = state.checkIn(this); }
public void freeze()  { state = state.freeze(this); }
public void resume()  { state = state.resume(this); }
public void renew()   { state = state.renew(this); }
public void expire()  { state = state.expire(this); }

Pros

  • Each state's rules live together, in one place
  • Transitions can be read in the code, since each state says which one comes next
  • A new state is one more constant, without touching the others' methods

Cons

  • With two states and one rule, an if is clearer
  • Transitions end up spread across the states; to see the whole map you have to read them all
  • The context has to open up to the states whatever they need to change (here, useTrialVisit()), which adds methods to it

← State · Run it