State Pattern
# State Pattern
In the State Pattern, the behavior of a class changes based on its state. This type of design pattern falls under the behavioral pattern category.
In the State Pattern, we create objects representing various states and a context object whose behavior changes as the state objects change.
The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class. By encapsulating each state into a separate class, it avoids using a large number of conditional statements to implement state transitions.
## Introduction
### Intent
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
### Main Problem Solved
* The State Pattern addresses the problem where an object's behavior depends on its state, allowing the object to switch behavior when its state changes.
### Use Cases
* When there are numerous conditional statements in the code that depend on the object's state.
### Implementation Approach
* **Define a State Interface**: Declare one or more methods to encapsulate the behavior of a specific state.
* **Create Concrete State Classes**: Implement the State interface, providing specific behavior based on the state.
* **Define a Context Class**: Contains a reference to a state object and updates its behavior when the state changes.
### Key Code
* **State Interface**: Declares behavior methods.
* **Concrete State Class**: Implements the State interface, encapsulating specific behavior.
* **Context Class**: Maintains a state object and provides methods to change its state.
### Application Examples
* **Basketball Player States**: A player can be in normal, abnormal, or super states.
* **Zenghouyi Bells**: The bells act as the context, with different bells (states) producing different playing effects.
### Advantages
* **Encapsulates State Transition Rules**: The logic for state transitions is encapsulated within the state objects.
* **Easy to Extend**: Adding new state classes does not affect existing code.
* **Centralizes State-Related Behavior**: All behavior related to a specific state is centralized in one class.
* **Simplifies Conditional Statements**: Avoids using a large number of conditional statements to switch behavior.
* **State Sharing**: Allows multiple context objects to share the same state object.
### Disadvantages
* **Increases Number of Classes and Objects**: Each state requires a concrete state class.
* **Complex Implementation**: The pattern structure and implementation are relatively complex.
* **Limited Support for Open/Closed Principle**: Adding new states or modifying state behavior may require modifying existing code.
### Usage Recommendations
* Consider using the State Pattern when an object's behavior changes with its state.
* The State Pattern is suitable for replacing complex conditional or branching statements.
### Notes
* The State Pattern is suitable for situations with a limited number of states (usually no more than 5).
* Use it judiciously to avoid making the system overly complex.
### Structure
The State Pattern includes the following main roles:
* **Context**: Defines the interface of interest to clients and maintains a reference to a current State object. The context can delegate state-related behavior to the state object.
* **State**: Defines an interface for encapsulating the behavior associated with a particular state of the context.
* **Concrete State**: Implements the State interface and is responsible for handling behavior associated with that state. A concrete state object typically maintains an internal reference to the context object to allow switching to different states based on various conditions.
## Implementation
We will create a _State_ interface and concrete state classes that implement the _State_ interface. _Context_ is a class with some state.
_StatePatternDemo_, our demo class, uses _Context_ and state objects to demonstrate the behavior change of the Context when the state changes.

### Step 1
Create an interface.
## State.java
public interface State{public void doAction(Context context); }
### Step 2
Create concrete classes implementing the interface.
## StartState.java
public class StartState implements State{public void doAction(Context context){System.out.println("Player is in start state"); context.setState(this); }public String toString(){return"Start State"; }}
## StopState.java
public class StopState implements State{public void doAction(Context context){System.out.println("Player is in stop state"); context.setState(this); }public String toString(){return"Stop State"; }}
### Step 3
Create the _Context_ class.
## Context.java
public class Context{private State state; public Context(){state = null; }public void setState(State state){this.state = state; }public State getState(){return state; }}
### Step 4
Use _Context_ to see behavior change when the _State_ changes.
## StatePatternDemo.java
public class StatePatternDemo{public static void main(String[]args){Context context = new Context(); StartState startState = new StartState(); startState.doAction(context); System.out.println(context.getState().toString()); StopState stopState = new StopState(); stopState.doAction(context); System.out.println(context.getState().toString()); }}
### Step 5
Execute the program, output the result:
Player is in start state Start StatePlayer is in stop state Stop State
* * *
## More Articles
YouTip