Interview frequency: …
Short answer
The difference is intent: Strategy represents independent algorithms from which a client chooses, while State represents internal behavior that changes automatically as the object's internal state changes, without the client's involvement.
Explanation
In Strategy, different strategies are unaware of each other and do not decide when to switch; the caller selects the required algorithm, such as a cash or card payment strategy. In State, an object's different states know about each other and handle automatic transitions, such as an order lifecycle of Draft -> Paid -> Shipped.
Code example
// State: State changes internally
class DraftState implements OrderState {
next(order: Order) { order.setState(new PaidState()); }
}
// Strategy: The client passes the algorithm
const sorter = new Sorter(new QuickSortStrategy());Common mistakes
- Using huge if/else chains to manage complex states, making the code difficult to maintain and extend with new states.