Skip to main content

How does State differ from Strategy?

The State and Strategy patterns look very similar: in both, an object's behavior is delegated to separate classes implementing a common interface. But their goals and contexts of use are fundamentally different.


1. The Main Idea

CriterionStateStrategy
What changesThe object's behavior depending on its stateThe algorithm the object uses depending on the client's choice
Who choosesThe object itself (internal logic)The client (external code)
GoalSimplify switching states and remove if-elseEncapsulate different algorithms and make them interchangeable
Behavior changeAutomatic (via internal transitions)Explicit (by a user's or code's decision)

2. The Mechanism

State

The object itself holds a reference to the current state and switches it itself when its internal state changes.

The context manages itself: "I'm in state X, now I need to move to Y".

java
class Context { private State state; public void setState(State s) { this.state = s; } public void request() { state.handle(this); } }

States can change the context:

java
class ConcreteStateA implements State { public void handle(Context c) { c.setState(new ConcreteStateB()); } }

Strategy

The context receives the strategy from outside and doesn't manage it. The choice of algorithm is made by the client, manually.

The client decides: "Use the ascending sort strategy."

java
class Context { private Strategy strategy; public Context(Strategy s) { this.strategy = s; } public void execute() { strategy.doAlgorithm(); } }

3. An Example of the Difference

State: an ATM

  • States: No card, Card inserted, No money.
  • The ATM switches states itself depending on user actions.
  • The client doesn't manage the states directly.

The behavior changes automatically based on internal logic.


Strategy: file compression

  • Strategies: ZIP, RAR, 7Z.
  • The client chooses the needed strategy before execution.

The behavior changes by the user's choice.


4. Analogy

SituationStateStrategy
A coffee machineAutomatically switches from "waiting" to "pouring coffee" and backThe user chooses which coffee to brew
A player in a gameMoves itself from "alive" → "wounded" → "dead"The user decides which weapon to attack with

5. The Key Differences in One Sentence

  • State manages internal transitions of an object's behavior.
  • Strategy provides an external choice of behavior algorithm.

Conclusion

Both patterns use delegation and interfaces, but:

  • State models a dynamic change of behavior by state;
  • Strategy is a flexible choice of algorithm from outside.

Summary:

State: an object lives and changes itself over time. Strategy: an object uses a chosen way of acting.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.