<< Chapter < Page | Chapter >> Page > |
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 intrinsically 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.
But does the user of the Sky class care about the stratregy?
Of course not. The user only cares that it does its job.
One design pattern that is used very often in conjunction with the state pattern is the Null Object Pattern .
Notice these things about the pattern:
Notification Switch
Would you like to follow the 'Design patterns' conversation and receive update notifications?