State
This pattern is used in computer programming to represent the state of an object. This is a clean way for an object to partially change its type at runtime. Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Objects are often discussed in terms of having a "state" that describes their exact conditions in a given time, based upon the values of their properties. The particular values of the properties affect the object's behavior. For instance, one can say that the exact behavior of an object's getColor() method is different if the "color" property of the given object is set to "blue" instead of "red" because getColor() returns a different value in the two situations.
Furthermore, the object may make decisions at run time as to exactly what to do dependent upon the values its properties possess. For instance, if the sky is blue (sky.setColor(Color.blue)), then the sun should be visible.
public boolean sunIsVisible()
{
if(getColor()==Color.blue)
{
return true;
}
else
{
return false;
}
}
One issue with the above solution is that it is a hard-coded logic solution, not an architected solution. The sky does not intrinisically behave a certain way if it is blue, but rather it should figure out what to do in that situation.
Wouldn't it be better if the sky intrinsically acted properly if it were blue? One could imagine two objects: a SkyBlue and a SkyNonBlue. The SkyBlue class' sunIsVisible() method would always return true while the SkyNonBlue version would always return false.
What one needs now is the ability for a sky object to dynamically (i.e. at run time) change its class to/from SkyBlue and SkyNonBlue. What we'd like to accomplish is called "dynamic reclassification".
We've seen code that does change its specific behavior depending on what particular strategy was installed. So, the setColor() method could install a strategy that would always return true if its sunIsVisible() method were to be called.
