Comparison
State patternvsStrategy pattern
State pattern
the object's behaviour changed after a call and nothing branched — it had swapped the object it was delegating to.
Representing each state of an object as a separate class implementing a shared interface, with the object delegating to its current one. It looks structurally identical to strategy, and the difference is who does the choosing: a strategy is handed in by the client and stays, a state replaces itself as the object moves through its lifecycle. That self-transition is the whole distinction and the whole interview answer.
Full entry →Strategy pattern
the class takes the algorithm as a constructor argument, and choosing a different one is a different argument.
Putting an interchangeable algorithm behind an interface so the object using it does not know which one it has. It is the pattern the caller chooses — a pricing rule, a sort comparator, a retry policy passed in from outside. In a language with first-class functions a strategy is usually just a function parameter, and saying so is a better answer than drawing the class diagram.
Full entry →