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
| Criterion | State | Strategy |
|---|---|---|
| What changes | The object's behavior depending on its state | The algorithm the object uses depending on the client's choice |
| Who chooses | The object itself (internal logic) | The client (external code) |
| Goal | Simplify switching states and remove if-else | Encapsulate different algorithms and make them interchangeable |
| Behavior change | Automatic (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".
class Context {
private State state;
public void setState(State s) { this.state = s; }
public void request() { state.handle(this); }
}States can change the context:
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."
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
| Situation | State | Strategy |
|---|---|---|
| A coffee machine | Automatically switches from "waiting" to "pouring coffee" and back | The user chooses which coffee to brew |
| A player in a game | Moves 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 readyA concise answer to help you respond confidently on this topic during an interview.