> For the complete documentation index, see [llms.txt](https://javascript-1.gitbook.io/design-pattern/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://javascript-1.gitbook.io/design-pattern/behavioural-design-pattern/state.md).

# State

Alter an object's behavior when its state changes.

* The State pattern provides state-specific logic to a limited set of objects in which each object represents a particular state.
* In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.

```javascript
EX:
class AlertStateContext { 
    private currentState;  
    public AlertStateContext()  
    { 
        currentState = new Vibration(); 
    }  
    public setState(state)  
    { 
        currentState = state; 
    }  
    public alert()  
    { 
        currentState.alert(this); 
    } 
} 
  
class Vibration {
    public alert(AlertStateContext ctx)  
    { 
         System.out.println("vibration..."); 
    }  
} 
  
class Silent {
    public void alert(AlertStateContext ctx)  
    { 
        System.out.println("silent..."); 
    }  
} 
  
function run() {
    AlertStateContext stateContext = new AlertStateContext(); 
    stateContext.alert(); // vibration...
    stateContext.alert(); // vibration...
    stateContext.setState(new Silent()); 
    stateContext.alert(); // silent...
    stateContext.alert(); // silent...
    stateContext.alert(); // silent...
}

run();
```
