CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 5 of 6 · 2 min read

State versus Strategy

Same shape, different aim.

State versus Strategy

State and Strategy have the same structure: a context holds a reference to an interface, and implementations of it are swapped. The difference is in intent and in who does the swapping.

Strategy State
Who changes it The client, from outside The states or the context, as events happen
Do the objects know each other No, strategies are independent Often yes, a state names its successors
Why it varies A choice of algorithm The object's own stage of life
Typical lifetime Set once, rarely changed Changes many times

A parking fee rule is a strategy. The parking ticket moving from issued to paid to exited is a state machine. If the object changes its own behaviour as a consequence of what happens to it, think State.

When to use State: an object with several states, behaviour that differs by state, and conditionals on the state in several methods. When not to: two states with one small difference, where a boolean and one if is simpler.

Interview angle

Answer in your head first, then open it.

What is the State pattern?

Each state is its own class with the same interface, and the context delegates to the current state object. Events change the state by switching the object.

How is it different from Strategy?

Strategy is chosen by the client and does not change by itself. State changes as the object lives.

Where would you use it?

Vending machines, ATMs, orders, bookings, elevators and TCP connections.

Check yourself: 1. Who changes the object in Strategy and in State? 2. When is a boolean better than State?

Words you will meet

Word Meaning
State One stage in an object's life, with its own behaviour
Transition A move from one state to another
Event Something that happens and may cause a transition
State machine A design with fixed states and rules for moving between them
Context The object that holds the current state