{{short description|Software design pattern}} The '''state pattern''' is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern's interface.
The state pattern is used in computer programming to encapsulate varying behavior for the same object, based on its internal state. This can be a cleaner way for an object to change its behavior at runtime without resorting to conditional statements and thus improve maintainability.<ref name="GOF">{{cite book |author=Erich Gamma |author2=Richard Helm |author3=Ralph Johnson |author4=John M. Vlissides |title=Design Patterns: Elements of Reusable Object-Oriented Software |publisher=Addison-Wesley |year=1995 |isbn=0-201-63361-2|title-link=Design Patterns: Elements of Reusable Object-Oriented Software }}</ref>{{Rp|395}}
==Overview== thumb|right|A sample UML class and sequence diagram for the State design pattern.<ref>{{cite web |title=The State design pattern – Structure and Collaboration |url=http://w3sdesign.com/?gr=b08&ugr=struct |website=w3sDesign.com |access-date=2017-08-12}}</ref> The state design pattern is one of twenty-three design patterns documented by the Gang of Four that describe how to solve recurring design problems. Such problems cover the design of flexible and reusable object-oriented software, such as objects that are easy to implement, change, test, and reuse.<ref name="GoF">{{cite book |author=Erich Gamma |author2=Richard Helm |author3=Ralph Johnson |author4=John Vlissides |title=Design Patterns: Elements of Reusable Object-Oriented Software |year=1994 |publisher=Addison Wesley |isbn=0-201-63361-2 |pages=[https://archive.org/details/designpatternsel00gamm/page/305 305ff] |url-access=registration |url=https://archive.org/details/designpatternsel00gamm/page/305 }}</ref>
The state pattern is set to solve two main problems:<ref>{{cite web |title=The State design pattern - Problem, Solution, and Applicability |url=http://w3sdesign.com/?gr=b08&ugr=proble |website=w3sDesign.com |access-date=2017-08-12}}</ref> * An object should change its behavior when its internal state changes. * State-specific behavior should be defined independently. That is, adding new states should not affect the behavior of existing states.
Implementing state-specific behavior directly within a class is inflexible because it commits the class to a particular behavior and makes it impossible to add a new state or change the behavior of an existing state later, independently from the class, without changing the class. In this, the pattern describes two solutions: * Define separate (state) objects that encapsulate state-specific behavior for each state. That is, define an interface (state) for performing state-specific behavior, and define classes that implement the interface for each state. * A class delegates state-specific behavior to its current state object instead of implementing state-specific behavior directly.
This makes a class independent of how state-specific behavior is implemented. New states can be added by defining new state classes. A class can change its behavior at run-time by changing its current state object.
== Structure == thumb|right|400px|State in UML<ref name="GOF" /> In the accompanying Unified Modeling Language (UML) class diagram, the <code>Context</code> class doesn't implement state-specific behavior directly. Instead, <code>Context</code> refers to the <code>State</code> interface for performing state-specific behavior (<code>state.handle()</code>), which makes <code>Context</code> independent of how state-specific behavior is implemented. The <code>ConcreteStateA</code> and <code>ConcreteStateB</code> classes implement the <code>State</code> interface, that is, implement (encapsulate) the state-specific behavior for each state. The UML sequence diagram shows the run-time interactions:
The <code>Context</code> object delegates state-specific behavior to different <code>State</code> objects. First, <code>Context</code> calls <code>handle(this)</code> on its current (initial) state object (<code>ConcreteStateA</code>), which performs the operation and calls <code>setState(ConcreteStateB)</code> on <code>Context</code> to change context's current state to <code>ConcreteStateB</code>. The next time, <code>Context</code> again calls <code>handle(this)</code> on its current state object (<code>ConcreteStateB</code>), which performs the operation and changes context's current state to <code>ConcreteStateA</code>.
== Example == This is a C++ example demonstrating the state pattern. <syntaxhighlight lang=cpp> import std;
using std::unique_ptr;
// Abstract State class FanState { public: virtual void handleButtonPress(class Fan& fan) const = 0; virtual ~FanState() = default; };
// Context class Fan { private: unique_ptr<FanState> currentState; public: explicit Fan(unique_ptr<FanState> state): currentState{state} {}
void setState(unique_ptr<FanState> state) noexcept { currentState = state; }
void pressButton() noexcept { currentState->handleButtonPress(*this); } };
// Concrete States class OffState : public FanState { public: void handleButtonPress(Fan& fan) const override { std::println("Fan is OFF -> Switching to LOW speed."); fan.setState(std::make_unique<LowSpeedState>()); } };
class LowSpeedState : public FanState { public: void handleButtonPress(Fan& fan) const override { std::println("Fan is on LOW speed -> Switching to HIGH speed."); fan.setState(std::make_unique<HighSpeedState>()); } };
class HighSpeedState : public FanState { public: void handleButtonPress(Fan& fan) const override { std::println("Fan is on HIGH speed -> Turning OFF."); fan.setState(std::make_unique<OffState>()); } };
int main() { Fan fan(std::unique_ptr<OffState>());
// Simulate pressing the button several times fan.pressButton(); // OFF -> LOW fan.pressButton(); // LOW -> HIGH fan.pressButton(); // HIGH -> OFF fan.pressButton(); // OFF -> LOW
return 0; } </syntaxhighlight>
==See also== * Typestate analysis
== References == {{Reflist}}
{{Wikibooks|Computer Science Design Patterns|State|State implementations in various languages}}
{{Design Patterns Patterns}}
Category:Software design patterns Category:Articles with example Java code