What are the differences between the Strategy design pattern and the State design pattern? I was going through quite a few articles on the web but could not make out the dif
Strategy: the strategy is fixed and usually consists of several steps. (Sorting constitutes only one step and thus is a very bad example as it is too primitive in order to understand the purpose of this pattern). Your "main" routine in the strategy is calling a few abstract methods. E.g. "Enter Room Strategy", "main-method" is goThroughDoor(), which looks like: approachDoor(), if (locked()) openLock(); openDoor(); enterRoom(); turn(); closeDoor(); if (wasLocked()) lockDoor();
Now subclasses of this general "algorithm" for moving from one room to another room through a possible locked door can implement the steps of the algorithm.
In other words subclassing the strategy does not change the basic algorithms, only individual steps.
THAT ABOVE is a Template Method Pattern. Now put steps belonging together (unlocking/locking and opening/closing) into their own implementing objects and delegate to them. E.g. a lock with a key and a lock with a code card are two kinds of locks. Delegate from the strategy to the "Step" objects. Now you have a Strategy pattern.
A State Pattern is something completely different.
You have a wrapping object and the wrapped object. The wrapped one is the "state". The state object is only accessed through its wrapper. Now you can change the wrapped object at any time, thus the wrapper seems to change its state, or even its "class" or type.
E.g. you have a log on service. It accepts a username and a password. It only has one method: logon(String userName, String passwdHash). Instead of deciding for itself whether a log on is accepted or not, it delegates the decision to a state object. That state object usually just checks if the user/pass combination is valid and performs a log on. But now you can exchange the "Checker" by one that only lets priviledged users log on (during maintanace time e.g.) or by one that lets no one log on. That means the "checker" expresses the "log on status" of the system.
The most important difference is: when you have choosen a strategy you stick with it until you are done with it. That means you call its "main method" and as long as that one is running you never change the strategy. OTOH in a state pattern situation during the runtime of your system you change state arbitrarily as you see fit.