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)
classDiagram
direction LR
class Membership {
<<Context>>
-MembershipState state
+checkIn() void
+freeze() void
+renew() void
}
class MembershipState {
<<State>>
+checkIn(Membership m)* MembershipState
+freeze(Membership m) MembershipState
+resume(Membership m) MembershipState
+renew(Membership m) MembershipState
}
class TRIAL {
<<ConcreteState>>
}
class ACTIVE {
<<ConcreteState>>
}
class FROZEN {
<<ConcreteState>>
}
class EXPIRED {
<<ConcreteState>>
}
Membership o-- MembershipState
MembershipState <|-- TRIAL
MembershipState <|-- ACTIVE
MembershipState <|-- FROZEN
MembershipState <|-- EXPIREDParticipants
- 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