- State pattern
[
LePUS3 ( [http://lepus.org.uk/ref/legend/legend.xml legend] ) ]The state pattern is a behavioral
software design pattern , also known as the objects for states pattern. This pattern is used incomputer programming to represent the state of an object. This is a clean way for an object to partially change its type at runtimecite book | author=Gamma, Erich | coauthors = Richard Helm, Ralph Johnson, John M. Vlissides
title = Design Patterns: Elements of Reusable Object-Oriented Software
publisher = Addison-Wesley
date = 1995
pages = 395
isbn = 0201633612 ] .Take for example, a drawing program, in which there could be an
abstract interface representing a tool, thenconcrete instance s of that class could each represent a kind of tool. When the user selects a different tool, the appropriate tool would be instantiated.Interface Example
For example, an interface to a drawing tool could beThen a simple pen tool could be
A client using the state pattern above could look like this:The state of the drawing tool is thus represented entirely by an instance of AbstractTool. This makes it easy to add more tools and to keep their behavior localized to that subclass of
AbstractTool
.As opposed to using switch
The state pattern can be used to replace
switch()
statements andif {}
statements which can be difficult to maintain and are less type-safe. For example, the following is similar to the above but adding a new tool type to this version would be much more difficult.ee also
*
Finite State Machine
*Strategy pattern
*Dynamic classification External links
* [http://www.lepus.org.uk/ref/companion/State.xml State in UML and in LePUS3] (a formal modelling language)
* [http://www.fsw.com/Jt/Jt.htm Jt] J2EE Pattern Oriented Framework
* [http://www.lepus.org.uk/ref/companion/State.xml State pattern in UML and in LePUS3] (a formal modelling language)References
Wikimedia Foundation. 2010.